Question

I've got a ul of various items which can have one of several possible data-attribute values, like this:

<ul>
    <li id="li1" data-cat="one">test item
    <li id="li2" data-cat="one">test no 2
    <li id="li3" data-cat="two">test dummy
    <li id="li4" data-cat="three">test no 4
    <li id="li5" data-cat="three">more test
    <li id="li6" data-cat="three">test no 6
</ul>

I'm attempting to use jQuery to select the first item of each distinct data-cat value - so for this example, li#li1, li#li3, and li#li4. I've tried building an array of each element with the data-attribute, then sorting with .unique like this

var list = $( '[data-cat]' ).get();
listSorted = jQuery.unique( list );
$( listSorted ).addClass('active');

But the code just selected all elements (see fiddle here)

I've found answers on SO like this one that come close, but they all seem to rely on knowing the data-attribute value beforehand and searching for that specific value. Is it possible to select the first element with a particular data-cat value without specifying the values beforehand?

Était-ce utile?

La solution

var cats = {};
var list = $( '[data-cat]' ).filter(function(){
    var category = $(this).data("cat");

    if(cats[category]){
        // category already accounted for, return false
        return false;   
    } else {
        // first of this category
        cats[category] = true;
        return true;
    }
});

http://jsfiddle.net/nB3ru/5/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top