Reputation: 21062
Maybe I am missing something, but I use data-*
attribute, namely data-content
with such entries like "apple", "cow", etc. Suddenly I was hit when I set my data-content
with string "null" (I checked using Chromium HTML is:
<p class="text" data-content="null">null</p>
But when I read data-content
using jQuery:
text_elem.data('content')
I get null value, not "null" string.
So my question is, how to read it in raw form, so I could get "null" string exactly as it is in HTML?
Upvotes: 2
Views: 1971
Reputation: 37
The .find()
method could be use to search an XML document for the element name specified. For the HTML document, if you want to access the attribute you must use the .attr()
method.
Upvotes: 0
Reputation: 123739
If you want to read it in the raw form you would need to use .attr
instead of .data
. Because that is what data
api does it parses the content of the data attribute (ex JSON --> object, numeric string value to number etc...).
text_elem.attr('data-content');
Or you could use dataset (Not supported in older browsers) with the DOM element.
text_elem[0].dataset.content; //this will return a string
Upvotes: 6
Reputation: 10972
You get null
instead of "null"
because jQuery has for some reason decided to parse data-
attributes as JSON when fetching using .data()
.
To get the raw data, use .attr()
instead. This will be faster, and it doesn't make a copy of the value into jQuery.cache
, which is very often unnecessary.
Basically, only use .data()
for data-
attributes if you need the data stored in jQuery.cache
and if you're alright with it being parsed as JSON
.
Upvotes: 4