admin管理员组

文章数量:1355564

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.

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.

Share Improve this question asked Jun 1, 2015 at 16:19 GabrielGabriel 6111 gold badge10 silver badges26 bronze badges 3
  • "li:nth-child(1) a" ? – Felix Kling Commented Jun 1, 2015 at 16:21
  • Check this stack post – Suraj Palwe Commented Jun 1, 2015 at 16:22
  • do you mean you want to get them in a "live" state? or just after they have been created? – Vandervals Commented Jun 1, 2015 at 16:23
Add a ment  | 

3 Answers 3

Reset to default 4

But how can I select the <a> element inside the <li>?

Selector syntax includes the descendant binator, 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.

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');
document.querySelector("li:nth-child(1) a"); 

Will work

本文标签: javascripthow to use querySelector to select dynamic added elementsStack Overflow