Search code examples
javascriptjqueryhtmljquery-data

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.. e.g. className

.attr() sets/gets TAG ATTRIBUTES.. e.g. 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 i.e.) 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.


Solution

  • 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