user619656
user619656

Reputation: 799

Can't find element with a specific data dash attribute that I added dynamically

When I add a data-itemid attribute to an element, I can not find that element using

$('someSelector').find( '[data-itemid="' + itemid + '"]' )

Doing

$('#id-of-element-i-added-the-attribute-to').data('itemid')

returns the correct data.

$('#id-of-element-i-added-the-attribute-to').attr('data-itemid')

returns an empty string.

$('someSelector').find( '[data-itemid="' + itemid + '"]' ) works for elements that initially have that data dash attribute, but not for dynamically added attributes.

I add the attribute like this $('#'+listItemId).data('itemid', itemId);

How can i find the element that has that dynamically added data-itemid attribute with specific value.

This selectors don't work as well (they return empty arrays):

$('*').find( '[data-itemid="' + itemid + '"]' )
$('[data-itemid="' + itemid + '"]' )
$('[data-itemid="16"]' )

Upvotes: 3

Views: 3620

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use filter to find dynamically added data attributes. Try this:

var $elementsWithDataAttr = $('someSelector .class').filter(function() {
    return $(this).data('itemid') != "";
});
// do something with $elementsWithDataAttr ...

Upvotes: 7

Related Questions