How to find dynamically added element by data attribute using jQuery?

There is an element to which a data attribute is dynamically applied like this

var tr = $('<tr>');
tr.data('template_id', 5);
table.find('tbody').append(tr);

      

Here we have tr on the table.
...
Here we want to find our new tr attribute by attributes

var tr = table.find('[data-template_id="5"]');
console.log(tr) // tr.length = 0;

      

Unfortunately, we never found tr.
Why is he getting this result?

+3


source to share


3 answers


The problem is that attributes data-*

added via jQuery are stored in an internal cache. They are not available as attributes in the DOM. With this in mind, you can use filter()

to achieve what you need:



var $tr = table.find('tr').filter(function() {
    return $(this).data('template_id') == 5;
});
console.log($tr.length);

      

+9


source


Try tr.attr("data-template_id", 5)

instead tr.data('template_id', 5)

.



0


source


I think you can use

tr.attr('template_id', 5);

      

-1


source







All Articles