jQuery 1.4.4: How to find an element based on its data-attribute value?
Asked Answered
F

1

6

I imagine this should be a pretty trivial task but using Firefox for Mac, 3.6.12 the following does not work:

// assign data attributes
$('.gallery li').each(function(i) {
    $(this).data('slide',i+1);
});

// outputting an empty jQuery object
console.log($('.gallery li[data-slide]'));

// this does not work either outputting an empty jQuery object
console.log($("[data-slide]"));

using Firebug I can see that all the data-slide attributes including their numerical value are correctly attached to the lis and logging out:

$('.gallery li').each(function(index) {
  console.log($(this).data());
});

outputs as expected:

Object { slide=1}
Object { slide=2}
Object { slide=3}
Object { slide=4}

So why does the first console.log not work?

Fermentation answered 16/11, 2010 at 20:3 Comment(0)
H
9

data adds items to jQuery's internal data holder, not to the data- attributes. These are read into jQuery's data() structure, but values inserted using jQuery are not fed back into the DOM.

The easiest way to mimic this would be using .filter():

// To replicate $('.gallery li[data-slide]')
$('.gallery li').filter(function(){
    return (undefined !== $(this).data('slide'));
});

You could also do this as a custom selector:

$.expr[':'].hasData = function(obj, index, meta, stack) {
    return (undefined !== $(obj).data(meta[3]));
};

$('.gallery li:hasData(slide)'); // li elements under .gallery with "slide" data set
$(':hasData(slide)'); // any element with "slide" data set
Harmonicon answered 16/11, 2010 at 20:10 Comment(5)
ah okay, i had misunderstood the .data() function as a shortcut for the data-attribute in html5. So to read/write to those i will need to do $(el).attr('data-slide',1)?Fermentation
@Fermentation - if you aren't actually interested in data() and just want attributes, use .attr()Accessible
@Fermentation If you really want to. Why not use .data(), though? Much more flexible and powerful -- e.g. you can set values other than strings. Also note that data() won't be updated by using attr().Harmonicon
Thanks for the clarification! Super useful, once I switched things over to using .attr('data-* … it all works. What I still don't quite understand though is how the .data method is 'better' seeing as it makes it much harder finding elements based on their current data value? or am i missing something here…?Fermentation
@Fermentation Finding elements is not really what data attributes are for. They are quite simply for storing data. In this case, you should probably take the semantic approach and add a slide class, or something similar.Harmonicon

© 2022 - 2024 — McMap. All rights reserved.