Sebastien
Sebastien

Reputation: 2679

Select every first unique element by grouping

I have a list of elements which have alternating classes. The occurrences of the classes are random and can occur once or many times in a row.

I am looking a way to select every first occurrence of an element (marked with a -). Preferably, I'd like to do this in CSS but I can work with a JavaScript solution as well.

<div class="type-1"></div>  -
<div class="type-1"></div>
<div class="type-1"></div>
<div class="type-2"></div>  -
<div class="type-1"></div>  -
<div class="type-1"></div>
<div class="type-2"></div>  -
<div class="type-2"></div>
<div class="type-1"></div>  -
...

Upvotes: 3

Views: 78

Answers (2)

TW80000
TW80000

Reputation: 1515

Just like this: https://jsfiddle.net/aq8nw21f/

This code uses the CSS adjacent sibling selector, as well as :first-of-type to get the edge case of the first item in the list.

#container > div:first-of-type, .type-1 + .type-2, .type-2 + .type-1 {
  color: red;
}
<div id="container">
    <span>If you used :first-child, the div below this would not highlight.</span>
    <div class="type-1">Yes</div>
    <div class="type-1">No</div>
    <div class="type-1">No</div>
    <div class="type-2">Yes</div>
    <div class="type-1">Yes</div>
    <div class="type-1">No</div>
    <div class="type-2">Yes</div>
    <div class="type-2">No</div>
    <div class="type-1">Yes</div>
</div>

Upvotes: 5

Ori Drori
Ori Drori

Reputation: 192287

And a less spectacular JS solution than the CSS one of TW80000:

var els = Array.from(document.querySelectorAll('div[class^="type-"]'));

console.log(els.filter(function(el, index) {
  return index === 0 || !el.classList.contains(els[index - 1].classList.item(0));
}));
<div class="type-1">1</div>
<div class="type-1">2</div>
<div class="type-1">3</div>
<div class="type-2">4</div>
<div class="type-1">5</div>
<div class="type-1">6</div>
<div class="type-2">7</div>
<div class="type-2">8</div>
<div class="type-1">9</div>

Upvotes: 0

Related Questions