Search code examples
javascriptqueryselector

QuerySelector with specified index in Javascript (like [1])


How do I make:

document.getElementsByClassName("first")[1].getElementsByClassName("second")[2];

but with querySelector?


My guess would be:

document.querySelector(".first[1] > .second[2]");

But that doesn't work.


Solution

  • In your original selection you're grabbing the second element with the class of .first and the third element with the class of .second that is also the child of the former. With this in mind you could use the nth-of-type pseudo selector for both classes and count up accordingly. The only difference with this method in comparison to the JS you have now is that it doesn't use the zero-index.

    // document.getElementsByClassName("first")[1].getElementsByClassName("second")[2];
    
    document.querySelector('.first:nth-of-type(2) .second:nth-of-type(3)').style = 'border: 1px solid red;'
    .first {
      border: 1px solid black;
      padding: 10px;
    }
    
    .first:nth-of-type(2) {
      margin-top: 10px;
    }
    <div class="first">
      <div class="second">Second (1)</div>
      <div class="second">Second (2)</div>
      <div class="second">Second (3)</div>
    </div>
    
    <div class="first">
      <div class="second">Second (1)</div>
      <div class="second">Second (2)</div>
      <div class="second">Second (3)</div>
    </div>