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.
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.
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.
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".
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" ).
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;
}
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With