I have the following html:
<div class="container">
<div>Test1
<div>Test1.1</div>
<div>Test1.2</div>
<div>Test1.3</div>
</div>
<div>Test2
<div>Test2.1</div>
<div>Test2.2</div>
<div>Test2.3</div>
</div>
<div>Test3</div>
<div>Test4</div>
</div>
I'm trying to get to 'Test 2' using this:
var secondChilds = document.querySelectorAll(".container div:nth-child(2)");
console.log(secondChilds[0]);
However, this gets me:
<div>Test1.2</div>
Any idea what I am doing wrong? Thanks so much.
var secondChilds = document.querySelectorAll(".container div:nth-child(2)");
console.log(secondChilds[0]);
<div class="container">
<div>Test1
<div>Test1.1</div>
<div>Test1.2</div>
<div>Test1.3</div>
</div>
<div>Test2
<div>Test2.1</div>
<div>Test2.2</div>
<div>Test2.3</div>
</div>
<div>Test3</div>
<div>Test4</div>
</div>
querySelectorAll()
is returning 3 divs. Test1.2
is the second child of the Test1
div. Test2
is the 2nd child of the .container
div. And Test2.2
is the second child of the Test2
div.
Since it returns them in the order that they appear in the DOM, the one that you want is secondChilds[1]
, not secondChilds[0]
.
If you only want to consider direct children of .container
, not nested children, use >
.
var secondChilds = document.querySelectorAll(".container > div:nth-child(2)");
console.log(secondChilds[0].innerText);
<div class="container">
<div>Test1
<div>Test1.1</div>
<div>Test1.2</div>
<div>Test1.3</div>
</div>
<div>Test2
<div>Test2.1</div>
<div>Test2.2</div>
<div>Test2.3</div>
</div>
<div>Test3</div>
<div>Test4</div>
</div>