0

I want to be able to get a set of elements that match a selector in jQuery. I have HTML with data tag attributes that get altered dynamically by jQuery using the .data(key, value) method.

However, after dynamically updating an element's data tag it seems I can no longer use a selector to get that element with the updated value. It still returns the old value.

I have a JSFiddle setup to demonstrate this issue: https://jsfiddle.net/o6pnvqgv/1/

Here is the example code:

<span id="example" data-tag="5"></span>

<div id="result"></div>
<div id="result2"></div>

$(document).ready(function(){
    var $example = $('#example');

    $('#result').html($example.data('tag'));
    $example.data('tag', 7);

    $('#result').html("elements that have tag 5: " + $('[data-tag="5"]').length);

    $('#result2').html("elements that have tag 7: " + $('[data-tag="7"]').length);
});

RESULT:

elements that have tag 5: 1 elements that have tag 7: 0

I know I can use a each loop and compare data for each individual element through an if statement.. But I want to be able to query all elements by the new set data tag value and get those results back.

Any help?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dan
  • 2,323
  • 1
  • 21
  • 30

1 Answers1

2

Your question is answered here:

jQuery .data() Not Updating DOM

$('#foo li[data-my-key="54321"]') is a attribute selector.

Using .data(..) changes the elements properties which you cannot select from without using a filter.

If you want to get all the elements with a certain property you can do this (using filter(...)):

$('#foo li').filter(function(index) {
  return $(this).data('my-key') === 54321;
}); //returns all `#foo li` with data[my-key] === 54321

See here for more info: .prop() vs .attr()

Community
  • 1
  • 1
Bruno João
  • 5,105
  • 2
  • 21
  • 26