简体   繁体   中英

How to read raw content of data-* attribute using jQuery?

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?

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM