Using .data()
will only add data to the jQuery object for that element. In order to add the information to the element itself you need to access that element using jQuery's .attr
or native .setAttribute
$('div').attr('data-info', 1);
$('div')[0].setAttribute('data-info',1);
In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ($('div[data-info="1"]')
), but when you use .data()
you cannot. In order to select based on the .data()
setting, you would need to use jQuery's filter function.
$('div').data('info', 1);_x000D_
//alert($('div').data('info'));//1_x000D_
_x000D_
$('div').filter(function(){_x000D_
return $(this).data('info') == 1; _x000D_
}).text('222');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>1</div>
_x000D_