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
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
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; -->
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>
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.