select nth child from 2 levels up

Issue

I have an html structure like this:

<div class='parent'>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
</div>

so we have parent -> row -> button, 1 parent, 2 rows, each row has 2-4 buttons. is there a css selector I can use (like nth-child) but that treats all buttons as siblings (even if they’re in different rows)? Something like:

.parent .child:nth-child(randomNum) {

}

where randomNum is a number between 1 and numOfTotalButtons.length

Solution

I’m affraid that it is not possible using only CSS. You can archive this using jQuery or pure javascript :

//jQuery
$(".button").eq(0).css("color", "red");
$(".button").eq(1).css("color", "green");
//pure javascript
document.querySelectorAll(".button")[2].style.color = "blue";
document.querySelectorAll(".button")[3].style.color = "pink";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent'>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
  <div class='row'>
    <div class='button'>
      button
    </div>
    <div class='button'>
      button
    </div>
  </div>
</div>

Answered By – Tom

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.