0

How to hide one element when a duplicate element in existing.

<div class="example">Example</div>
<-- Lot of code here -->
<div class="example">Example</div> <!-- Hide this with CSS: display: none; -->

I think i need a Script

browntoast
  • 87
  • 1
  • 11
  • This has been answered already - http://stackoverflow.com/questions/6895197/hide-all-divs-except-first-one-having-same-class – adprocas Apr 10 '17 at 17:04

3 Answers3

2

If your structure will be like that always with the elements as siblings you can use the general sibling selector:

.example ~ .example {
  color:red;
}
<div class="example">Example</div>
<p>More code between siblings</p>
<div class="example">Example</div> <!-- Hide this with CSS: display: none; -->
DaniP
  • 37,813
  • 8
  • 65
  • 74
1

Little more complex answer. Following solution will catch all elements in your document that have a class attribute. It will count the amount of every element with specified class and will hide every element with the same class except the first one.

var allElems = document.querySelectorAll('*'),
    elems = [],
    obj = {};
    
    Array.from(allElems).forEach(v => v.getAttribute('class') ? elems.push(v) : null);
    elems.forEach(v => !obj[v.getAttribute('class')] ? obj[v.getAttribute('class')] = 1 :     obj[v.getAttribute('class')]++);
    Object.keys(obj).forEach(function(v) {
      var elements = document.getElementsByClassName(v);
      if (obj[v] > 1) {
        Array.from(elements).forEach(v => v.hidden = true);
        elements[0].hidden = false;
      }
    });
<div class="example">Example</div>
<div class="example">Example</div>
<div class="example">Example</div>
<div class="example">Example</div>

<div class="another">Another</div>
<div class="another">Another</div>

<div class="Alone">Alone</div>
kind user
  • 40,029
  • 7
  • 67
  • 77
1

To hide all divs with the class "example" except for the first div with that class you could use this jQuery,

$('.example:gt(0)').css('display','none');

Sets all divs with class "example" explicitly to display:none; with an index greater than 0.

Todd
  • 758
  • 1
  • 9
  • 20