Home > Back-end >  Access to cell attributes with row id
Access to cell attributes with row id

Time:01-06

I have the following table and jQuery code to create an object based on some columns/cells data-attributes:

<tbody>
    <tr id="1">
        <td data-name1="Name 1">Name 1</td>
        <td data-name2="Name 2">Name 2</td>
        <td data-name3="Name 3">Name 3</td>
    </tr>
    <tr id="2">
        <td data-name1="Name 1">Name 1</td>
        <td data-name2="Name 2">Name 2</td>
        <td data-name3="Name 3">Name 3</td>
    </tr>
</tbody>

Right now I have stored all the tr id's in a variable so I have this jQuery code:

for (var x = 0; x < idsVar.length; x  ) {
    var tdName1 = $(`#${idsVar[x]} > td`).attr('data-name1');
    var tdName2 = $(`#${idsVar[x]} > td`).attr('data-name2');
}

This code seems to work. The problem is that now I'm implementing jQuery DataTables library with default pagination and the problem I'm facing is that for example; if my table contains more than 1 page the above code only works for the rows on the current page, if I want to access to the rows from other page they doesn't exists for my jQuery code.

I was reading the DataTables documentation and seems that this code could help:

var table = $('#example').DataTable();
table.rows().nodes().etc...

But I think that code loops throught all the table rows and what I'm trying to do is only on some specific row ids. So my question is how can I access to a specific row id and some data attributes. Maybe something like:

table.rows('specificId').nodes('data-attribute') 
or 
table.rows('specificId').nodes().something to get the data attribute

CodePudding user response:

To access to a specific row by its ID you can use this:

var row = table.row('#idHere')

And for access to the data attributes of that row you can use this:

var row = table.row('#idHere').nodes()[0];
$(row).attr('data-attributeName');

Please go to datatable docs for more information.

  • Related