简体   繁体   中英

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

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

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

Here we have our tr on the table.
...
Here we want to find our newly added tr by data attribute

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

Unfortunately, we have no found tr this way.
Why it is getting this result?

The issue you have is that data-* attributes added via jQuery are stored in its internal cache. They are not available as attributes in the DOM. With that in mind, you can use filter() to achieve what you require:

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

尝试tr.attr("data-template_id", 5)而不是tr.data('template_id', 5)

我想你可以用

tr.attr('template_id', 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM