Justinas
Justinas

Reputation: 43557

Select element by data attribute after it's change

I have lot's of elements with pre-defined attribute data-key="foo". Now after updating this element value I also update it's data-key attribute ($(this).data('key', 'boo');). After that I can no longer select it using selector [data-key="boo"]. What am I doing wrong here?
I prefer no to loop all elements again and check it's data-key attribute value. Also as I understand :data(key) selector can't select elements by key and value?

$(document).ready(function() {
  $('[data-key="foo"]').data('key', 'boo');

  setTimeout(function() {
    $('[data-key="boo"]').css('color', 'green');
    $('#element').append(' - Now it must be green, because data-key now is ' + $('#element').data('key'));
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="foo" id="element">MAKE THIS GREEN</div>
<div data-key="boo" >data-key="boo" by default...</div>

Upvotes: 2

Views: 1998

Answers (1)

Satpal
Satpal

Reputation: 133453

When using .data(), it is stored in internal cache using $.cache not with attribute. So when using attribute value selector only one element is selected.

You can go through these post

  1. How does jQuery .data() work?
  2. Where is jQuery.data() stored?

If you want to use attributes to select element then use .attr() instead of .data()

$(document).ready(function() {
  $('[data-key="foo"]').attr('data-key', 'boo');

  setTimeout(function() {
    $('[data-key="boo"]').css('color', 'green');
    $('#element').append(' - Now it must be green, because data-key now is ' + $('#element').data('key'));
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="foo" id="element">MAKE THIS GREEN</div>
<div data-key="boo" >data-key="boo" by default...</div>


However if you still want to use .data() then you can use .filter() to identify elements.

$('[data-key="foo"]').data('key', 'boo');
setTimeout(function() {
  $('[data-key]').filter(function(){
    return $(this).data('key') == 'boo';
   }).css('color', 'green');
}, 1000);

$(document).ready(function() {
  $('[data-key="foo"]').data('key', 'boo');

  setTimeout(function() {
    $('[data-key]').filter(function(){
      return $(this).data('key') == 'boo';
     }).css('color', 'green');
    $('#element').append(' - Now it must be green, because data-key now is ' + $('#element').data('key'));
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="foo" id="element">MAKE THIS GREEN</div>
<div data-key="boo" >data-key="boo" by default...</div>

Upvotes: 6

Related Questions