Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery selector by data attribute when data is added dynamically?

I have a ul with several items. I populate the list dynamically after page load using jquery. As I add each list item, I also add an "itemID" to the data of that element using the jquery ".data()" function. Something like this:

var item = $('<li>My Item Name</li>');
item.data('itemID', '123ABC456');

Later, I need a selector to determine if there is any item in my item list with a specific itemID. First I tried using:

$('*[data-itemID="123ABC456"]');

This didn't work - and on further research, I discovered that this syntax only works if the data attribute was set in the DOM when the page was loaded; it doesn't work if you use the ".data" jquery method dynamically.

Next I tried:

$(':data(itemID==123ABC456)');

For some reason, this doesn't work. If I run simply $(':data(itemID)'), however, then I do get all the li elements that have an itemID in their data.

I know that the itemID attribute is set correctly, as when I call .data() on that list item I get:

Object { itemID="123ABC456"}

How can I select all elements that have an itemID of "123ABC456" in their data?

like image 209
froadie Avatar asked Jul 26 '12 14:07

froadie


1 Answers

http://jsfiddle.net/w28p9/1/ <-- jsFiddle example showing differences with data-attribute & jquery.data()

jQuery.data() is different than HTML5 data-NAME attributes which you are trying to search for.

http://api.jquery.com/jQuery.data/

jQuery.data() saves inside of the jquery element (this data is hidden from plain sight). Looking for [data-itemID] would work if inside of the actual had: <li data-itemID="12345"></li>.

To retrieve and look for the actual hidden .data() try:

// of course be more specific than just searching through all <li>'s
$('li').each(function () {
    if ( $(this).data('itemID') === '123ABC456' ) {
        // do whatever you wanted to do with it
    } 
});

Hope that helps!

like image 160
Mark Pieszak - Trilon.io Avatar answered Nov 02 '22 09:11

Mark Pieszak - Trilon.io