Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 368
Tobias H. Avatar asked Oct 28 '25 16:10

Tobias H.


2 Answers

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>
like image 146
Carl Edwards Avatar answered Oct 31 '25 07:10

Carl Edwards


document.querySelector(".first:nth-of-type(2) .second:nth-of-type(3)").style.color = "red"
<div class="first">
  <div class="second">second1</div>
  <div class="second">second2</div>
  <div class="second">second3</div>
  <div class="second">second4</div>
</div>
<div class="first">
  <div class="second">second1</div>
  <div class="second">second2</div>
  <div class="second">second3</div>
  <div class="second">second4</div>
</div>
like image 23
ikiK Avatar answered Oct 31 '25 05:10

ikiK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!