Spencer
Spencer

Reputation: 642

Add data attribute to table cell

Is it possible to add a data attribute to a table cell using jquery? I have the following but it doesn't add a data-attribute to the td.

$("td.row").each(function( index ) {
  $(this).data("rowid",index);
});

Any ideas?

Upvotes: 1

Views: 7279

Answers (1)

Shawn31313
Shawn31313

Reputation: 6052

.data() allows you to store data associated with an element. It does allow you to get the data from element with an already set data-* attribute, but it doesn't actually allow you to add data-* attributes to an element.

.attr() allows you to add this attribute though.

$("td.row").each(function( index ) {
    $(this).attr("data-rowid", index);
});

You can also use @CrazyTrain's solution which seems a little more efficient:

$("td.row").attr("data-rowid", function(index) { 
    return index;
});

Upvotes: 6

Related Questions