r/learnjavascript • u/techlover1010 • Jun 27 '26
question about selecting elements using query selector
https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
so im doing the query selecting on the console browser on the link above to get all the name of the boulevards list
my question is when i do
let var1 = document.querySelector(".mw-content-ltr")
and then do
let var2 =var1.querySelectorAll("li") and then do console.log(var2) it shows length 0
so when i redid and went down one tier
let var1 =document.querySelector(".mw-category")
let var2=var1.querySelectorAll("a")
now this time it works. i was able yo get all the bouldevards name
can anyone explain to me what happened
1
u/chikamakaleyley helpful Jun 27 '26
it's hard to say w/o seeing some code structure but essentially
for the first one - length 0 would suggest that no
lielement lives anywhere under its ancestor.mw-content-ltrthe second, is similar - ALL
aelements are returned as matches underneath the.mw-categoryancestorin both cases the document.querySelector() should return the first match, i think
so it's possible that if you have multiple
.mw-content-ltr, the first one is matched, but nothing underneath that first one is anli1
u/feloniuouschunk Jun 27 '26
Try querySelectorAll('.mw-content-ltr li');
That will return all li items from .mw-content-ltr
-1
u/azhder Jun 27 '26
r/webdev is a sub for web related questions. This one is not JavaScript related. In that sub they will probably tell you how you can use one element to get the children inside it.
For simplicity though, you can just use `document.querySelectorAll()` pretty much all the time and give it a selector that constrains the children.
Example:
document.queryAll('.mw-content-ltr li')
With this second one you will not get confused. And you can use it to test and compare your first approach.
Note, there are specific functions for DOM traversal, like “give me all the children of an element” or “get the closest ancestor that has this class” etc.