How to select elements with the same attribute value in jQuery?
Say I have a structure like this:
<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 divs with the same attribute except the first, so I would get:
<div data-stuff="foo"></div> <div data-stuff="bar"></div> <div data-stuff="baz"></div>
Now I know that I can just do this:
$('[data-stuff=foo]:gt(0), [data-stuff=bar]:gt(0), [data-stuff=baz]:gt(0)').hide();
The problem is that the value of data-stuff
dynamically generated and unpredictable. What can I do to complete this task?
EDIT
DOM elements are not necessarily the same, so $ .unique () will not help here. It is also important that the FIRST remains showy, so reordering cannot occur.
Firstly, rel
not used to store 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 list of link types, separated by spaces."
Secondly, rel
is just the attribute <a>
and <link>
. You really want to use the data-*
HTML5 attribute. Don't worry about browser support, it works all the way up to IE 66 (maybe 5).
This will be available through the jQuery $.data('name')
function.
<div data-foo="bar"></div>
will be available through:
$('div').filter(function(inputs){ return $(this).data('foo') === 'bar'; }).hide()
This means: if you select the first element, you want to hide all the brothers; So use the JBrothersByAttr
jquery plugin, which is part of the 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 with :eq(0)
var jq= $('[data-stuff=foo]:eq(0)')
2. Select other elements that have the same data-stuff
attr values โโthrough JBrothersByAttr
:
var brothers=jq.brothersByAttr('data-stuff')
3. Hide him
brothers.hide()