I’m encountering an issue with the querySelector method in JavaScript, specifically when attempting to access nested child elements. I have a selected element, and my goal is to retrieve the first child of the selected element and then obtain the first child of that inner element.
I’ve tried the following code:
let selected = document.querySelector(".main-box")
var desiredElement = selected.querySelector("div:nth-child(1) > div:nth-child(1)");
However, this seems to produce the same result as:
var desiredElement = selected.querySelector("div:nth-child(1)");
It appears that the second part of the selector (> div:nth-child(1)) is not behaving as expected.
My HTML structure is as follows:
<div class="main-box">
<div>
<div>Target Element</div>
<div></div>
<div></div>
</div>
<div>
<div></div>
<div></div>
<div></div>
</div>
<div>
<div></div>
<div></div>
<div></div>
</div>
</div>
but it works fine when I use this code
var desiredElement = document.querySelector(".main-box > div:nth-child(1) > div:nth-child(1)")
then why this code is not working
let selected = document.querySelector(".main-box")
var desiredElement = selected.querySelector("div:nth-child(1) > div:nth-child(1)");
2
Answers
The second part is supposedly to be your div with the inner text Target Element. The selection has to be a bit different because the
:nth-child()
selector selects child elements according to their position among all the sibling elements within a parent element.I already have tried this approach:
but it doesn’t give the desired effect as you want.
To my knowledge it probably has to do with the
:nth-child()
CSS pseudo-class which in this case doesn’t match with the index of the element in the child list of the parent.In other words, the div which you are trying to get through the querySelector here is probably wrong:
var desiredElement = selected.querySelector("div:nth-child(1) > div:nth-child(1)");
This approach is way more concise when you are dealing with children of other DOM elements.
In this instance, the easiest amendment you can make to your selector is to add a
:not(.main-box)
function to indicate that you don’t want the selector to start counting from.main-box
:Working Example: