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.

+6
source share
4 answers

Brute Force Method:

 var found = {}; $("[rel]").each(function(){ var $this = $(this); var rel = $this.attr("rel"); if(found[rel]){ $this.hide(); }else{ found[rel] = true; } }); 
+5
source

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/

+4
source

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() 
+2
source

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() 
0
source

Source: https://habr.com/ru/post/908658/


All Articles