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.
-
"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
3 Answers
Reset to default 4But 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
版权声明:本文标题:javascript - how to use querySelector to select dynamic added elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743931793a2563979.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论