Kyle Macey
Kyle Macey

Reputation: 8154

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.

Upvotes: 7

Views: 7916

Answers (4)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93253

That is means : if you select the first element , you want to hide each brothers ; So use JBrothersByAttr jquery plugin which is a part of Mounawa3et منوعات Jquery plugin:

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

Demo : http://jsfiddle.net/abdennour/7ypEa/1/

Explanation : 1. select the first via :eq(0)

   var jq= $('[data-stuff=foo]:eq(0)')

2.select the others elements that have the same value of data-stuff attr via JBrothersByAttr :

   var brothers=jq.brothersByAttr('data-stuff')

3.Hide it

brothers.hide()

Upvotes: 0

Chris Sobolewski
Chris Sobolewski

Reputation: 12945

Firstly, rel is not used for storing data. According to the W3C, rel describes "the relationship from the current document to the anchor specified by the href attribute. The value of this attribute is a space-separated list of link types."

Secondly, rel is only an attribute on <a> and <link>. You really want to be using the data-* HTML5 attribute. Don't worry about browser support, it works all the way back to IE 66 (probably 5).

This will be accessable via the JQuery $.data('name') function.

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

will be accessable via:

$('div').filter(function(inputs){
    return $(this).data('foo') === 'bar';
}).hide()

Upvotes: 2

James Montagne
James Montagne

Reputation: 78650

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;
    }
});

Upvotes: 6

gen_Eric
gen_Eric

Reputation: 227270

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/

Upvotes: 4

Related Questions