0

I want to select the the first div with con and car among all the div using css selector.

<div class="box">
  <div class="con">1</div>
  <div class="con be">2</div>
  <div class="con car">3</div>
  <div class="con">4</div>
  <div class="con be">5</div>
  <div class="con car">6</div>
</div>

And the con and car div can be in any place. Since it's the 3rd child right now I can call it by putting nth child as 3rd child. But it is the first div with con and car class. I may add more con and car class div's but I want to be able to select and style the first con and car div despite it's position. How can I do that??

Maisha Maliha
  • 69
  • 1
  • 1
  • 8
  • Not possible. Have a look at https://stackoverflow.com/a/8539107/151509 and see if you can find workarounds. – maryisdead Jan 16 '19 at 13:48

1 Answers1

2

One possible solution is to target the classes you DON'T want to style using the subsequent-sibling combinator ~

.con.car ~ .con.car {
  background: none;
}

.con.car {
  background: red;
}
<div class="box">
  <div class="con">1</div>
  <div class="con be">2</div>
  <div class="con car">3</div>
  <div class="con">4</div>
  <div class="con be">5</div>
  <div class="con car">6</div>
</div>

However, this is done much more simply using JavaScript

document.getElementsByClassName("con car")[0].style.background = "red";
<div class="box">
  <div class="con">1</div>
  <div class="con be">2</div>
  <div class="con car">3</div>
  <div class="con">4</div>
  <div class="con be">5</div>
  <div class="con car">6</div>
</div>
bskool
  • 2,068
  • 2
  • 17
  • 24