jquery

unique attribute values with jquery


is there a way to get all the unique values for a certain attribute.

e.g

<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="dog"></div>
<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="cat"></div>
<div class="bob" data-xyz="fish"></div>

I need to get all the distinct values for data-xyz attribute on div.bob,

so it should return fish, dog and cat.


Solution

  • Small code: Create an object and make 'dog' 'fish' 'cat' properties. That will make them unique. Then get the unique property names from the object. Simple and easy:

    var items = {};
    document.querySelectorAll('div.bob').forEach(function(element) {
        items[element.dataset['xyz']] = true; 
    });
    
    var result = new Array();
    for(var i in items)
    {
        result.push(i);
    }
    alert(result);
    

    Note, the original answer from 2011 and the Fiddle used jQuery to find and iterate the elements and to read the data attribute, but it's just as easy using JavaScript as shown above.

    Old loop:

    $('div.bob').each(function() {
        items[$(this).attr('data-xyz')] = true; 
    });
    

    http://jsfiddle.net/GxxLj/1/