简体   繁体   中英

javascript: html5 getting and setting data-*

I've used

var activeFilter = $('<li></li>').data('input-id', 'mycustomId');
$('#container').append(activeFilter);

Now I need to get the particular < li > element out of multiple < li > elements in known < ul >.

However the obvious selector doesn't work.

var existing = $('li[data-input-id=mycustomId]');
alert(existing.length);

Useful links: .prop() vs .attr() How to get, set and select elements with data attributes?

Summary:

.prop() sets/gets DOM properties.. eg className

.attr() sets/gets TAG ATTRIBUTES.. eg class, thus making selectors $('obj[class=xxx]') possible.

.data() sets/gets jQuery internal Cache attributes and doesn't map onto attributes or properties.

HOWEVER , in html5 ATTRIBUTES set with .attr() and containing prefix "data-" are being correctly accessible with .data() , BUT NOT VICE VERSA!!

http://jsfiddle.net/wjEvM/

In debugger there is NO property data-input-id listed, but it's accessible through

$('#container li:firstchild').data('input-id');

The question is how do I get (which selector do I have to use) the li (object ie) with given value of dataset, like obj.getChildWithData('data-id', 'mycustomId'); OTHER THAN in a loop checking each li's dataset. Or using stupid document.querySelectorAll, because it doesn't do what is needed.

Please explain if applicable if it supposed to work so. Getting data-* attributes set as attributes doesn't allow me to use .data() which is recommended by html5. So I want go get it right.

You are using attribute selector here, this works if you set your HTML5 data as this:

activeFilter.attr('data-input-id', 'mycustomId');

But, you should acces it using correct synthax:

$('#container li:firstchild').data('inputId');

And to answer to your comment, you can retrieve it using .filter():

var existing = $('li').filter(function(){return $(this).data('inputId') === "mycustomId"});

SEE DEMO

Unfortunately for your method, jQuery does not store data set via .data() in the DOM node's data attribute (see this question ).

Instead, you'll want to set it with .attr() , and then you can use $('li[data-input-id=mycustomId]') :

$('<li></li>').attr('data-input-id', 'mycustomId');

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