How do I access a custom HTML5 data- attribute in columnDefs render function?

How do I access a custom HTML5 data- attribute in columnDefs render function?

badazzkebadazzke Posts: 2Questions: 1Answers: 0

I am initialising a data table on HTML(DOM) sourced data with the following format

<table id="example" class="table >
    <thead>
        <tr>
            <th>Product</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td data-id ="12">Blue Shirt</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th>Service</th>
        </tr>
    </tfoot>
</table>

I then want to access the custom "data-id" attribute in the columnDefs renderer in the format below

columnDefs: [
                {
                    targets: [0],
                    render: function(data, type, row, meta) {
                        if(type === 'display'){
                            data = '<a target="_blank" href="/myurl.com?id='+data_id+'&whence=">'+data+'</a>';
                        }

                        return data;
                    }
                }],

Any help/suggestion on how I should go about this?
Also, I'm avoiding using the hidden columns option.
Any help will be much appreciated

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,181Questions: 26Answers: 4,924
    Answer ✓

    columns.render is not meant to access the actuals cells HTML. Its geared towards manipulating the table data. You might be able to use the meta parameter and access the API then use that, along with meta.row and meta.col to access the cell().node().

    Maybe something like rowCallback, createdRow or columns.createdCell will work.

    Maybe we can help guide you to the best solution. Please describe what you are wanting to do with the HTML5 data.

    Kevin

  • badazzkebadazzke Posts: 2Questions: 1Answers: 0
    edited April 2021

    Hi @kthorngren

    Using the advice you've provided I have managed to make it work by implementing the below in the columnDefs renderer function

    var table_api = new $.fn.dataTable.Api( meta.settings );
    var cell = table_api.cell(meta.row, meta.col).node();
    var record_id = $( cell ).attr( "data-id" );
    

    I then use the record_id as a parameter in the formatted cell url data in the format

    '<a target="_blank" href="www.myurl.com?id='+record_id+'">'+data+'</a>';

    Thank you very much for the assistance.
    Any better alternatives to the solution above are also welcome

This discussion has been closed.