I'm having some trouble with data-attributes, I can't get anything to work for some reason so I must be doing something wrong:
Set:
$('#element').data('data1', '1'); //Actually in my case the data is been added manually
Does that make a difference?
Get:
$('#element').data('data1');
Select:
$('#element[data1 = 1]')
None of this works for me, am I making this up or how is it?
To reflect the values of the Attributes immediately in the DOM you can use
.attr()
In plain Javascript you can try this
All of the answers are correct, but I want to state something that nobody else did.
The jQuery
data
method acts like a getter for html5 data attributes, but the setter does not alter the data-* attribute.So, If you manually added the data (as is stated in your comment), then you can use a css attribute selector to select your element :
but if you have added (altered) the data via jQuery, then the above solution won't work.
Here's an example of this failure :
So the workaround is to filter the collection by checking the jQuery data value to match the desired one :
So, in order to overcome these issues, you need to use the html5 dataset attributes (via jQuery's
attr
methos) as getters and setters :or you can use a custom expression that filters jQuery internal
data
:and use it like :
You are using ID selector so there is no need to use attribute selector, as data is a property and you are setting it using
data
method (not attr method) you cannot select the element using attribute selector, if you want to select the element only if it hasdata1 === 1
you can use thefilter
method: