Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select elements with the same attribute value in jQuery?

Say I have a structure like so:

<div data-stuff="foo"></div>
<div data-stuff="foo"></div>
<div data-stuff="foo"></div>
<div data-stuff="bar"></div>
<div data-stuff="bar"></div>
<div data-stuff="bar"></div>
<div data-stuff="baz"></div>

And I want to hide all the divs with the same attribute except the first, so I'd get:

<div data-stuff="foo"></div>
<div data-stuff="bar"></div>
<div data-stuff="baz"></div>

Now I know I could just do this:

$('[data-stuff=foo]:gt(0), [data-stuff=bar]:gt(0), [data-stuff=baz]:gt(0)').hide();

The problem is, the value of data-stuff is dynamically generated and is unpredictable. What could I do to accomplish this task?

EDIT

The DOM elements themselves aren't necessarily the same, so $.unique() won't help here. It's also important that the FIRST is the one that remains showing, so reordering can't happen.

like image 753
Kyle Macey Avatar asked Feb 16 '12 20:02

Kyle Macey


People also ask

Does jQuery support selection based on attributes values?

jQuery [attribute|=value] Selector The [attribute|=value] selector selects each element with a specified attribute, with a value equal to a specified string (like "en") or starting with that string followed by a hyphen (like "en-us"). Tip: This selector is often used to handle language attributes.

How do you find the element based on a data attribute value?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

How do you select an element by attribute?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

How get data attribute value in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).


2 Answers

The brute force way:

var found = {};

$("[rel]").each(function(){
    var $this = $(this);
    var rel = $this.attr("rel");

    if(found[rel]){
        $this.hide();
    }else{
        found[rel] = true;
    }
});
like image 183
James Montagne Avatar answered Nov 09 '22 18:11

James Montagne


How about something like this:

$('div[rel]:visible').each(function(){
    var rel = $(this).attr('rel');
    $(this).nextAll('div[rel="'+rel+'"]').hide();
});

DEMO: http://jsfiddle.net/CsTQT/

like image 28
Rocket Hazmat Avatar answered Nov 09 '22 18:11

Rocket Hazmat