Reputation: 611
I have a dom like this:
<ul>
<li><a>test</a></li>
<li><a>test</a></li>
<li><a>test</a></li>
<li><a>test</a></li>
</ul>
the <li>
element are added to the html dynamically so that I cannot add id to it.
And I'm using css selector to select the <li>
element by using:
document.querySelector("li:nth-child(1)")
But how can I select the <a>
element inside the <li>
? Can I do a querySelector inside anther querySelector? Or there's some better ways to do it? Thanks.
Upvotes: 3
Views: 15413
Reputation: 944171
But how can I select the
<a>
element inside the<li>
?
Selector syntax includes the descendant combinator, which is a space
document.querySelector("li:nth-child(1) a")
Can I do a querySelector inside anther querySelector?
The querySelector
method appears on all HTML elements. You can chain them:
document.querySelector("li:nth-child(1)").querySelector('a');
… which you probably shouldn't in this case.
If you were selecting multiple elements (with querySelectorAll
) then this would be less viable as you would have to loop over the first set of results and then query the descendants of each one.
Using native selector syntax is usually easier and clearer.
Upvotes: 4
Reputation: 55782
Can I do a querySelector inside anther querySelector?
Yes
document.querySelector('li:nth-child(1)').querySelector('a');
Or there's some better ways to do it?
Yes
document.querySelector('li:nth-child(1) a');
Upvotes: 1