admin管理员组文章数量:1307837
How can I select the 2nd <a>
tag using pure Javascript?
<div class="navigation">
<a href="/page/2/">Prev</a>
<a href="/page/4/">Next</a>
</div>
How can I select the 2nd <a>
tag using pure Javascript?
<div class="navigation">
<a href="/page/2/">Prev</a>
<a href="/page/4/">Next</a>
</div>
Share
Improve this question
edited Sep 29, 2015 at 19:45
Jordan Davis
1,5207 gold badges24 silver badges42 bronze badges
asked Sep 29, 2015 at 18:33
MartinDK81MartinDK81
3272 gold badges8 silver badges16 bronze badges
1
-
There are multiple possibilities:
document.querySelectorAll('.navigation a')[1]
,document.querySelector('.navigation').children[1]
,document.querySelectorAll('.navigation a:nth-child(2)')
,document.getElementsByClassName('navigation')[0].children[1]
. Depends on your use case. – Sebastian Simon Commented Sep 29, 2015 at 18:39
1 Answer
Reset to default 6Use the DOM selector getElementsByClassName().
Return Value: an array of elements containing the class name.
Replace the [?]
with the index of the target from the return value of the the getElementsByClassName
selector. For example, if the the <div>
tag containing the <a>
tags was the first element of the document with the class name navigation
then it would be at index 0
(since it's 0 based) of the return array, therefore you should use [0]
for the corresponding element.
Use the .children property to return an HTMLCollection of the child nodes (in this case <a>
tags) of which their parent node (in this case the <div>
tag).
//JS
document.getElementsByClassName('navigation')[1].children[1];
//HTML
<div class="navigation">
<a href="/page/1/">Prev</a>
<a href="/page/2/">Next</a>
</div>
<div class="navigation">
<a href="/page/3/">Prev</a>
<a href="/page/4/">Next</a> (selected element)
</div>
<div class="navigation">
<a href="/page/5/">Prev</a>
<a href="/page/6/">Next</a>
</div>
<div class="navigation">
<a href="/page/7/">Prev</a>
<a href="/page/8/">Next</a>
</div>
本文标签: javascriptSelecting a child node (DOM)Stack Overflow
版权声明:本文标题:javascript - Selecting a child node (DOM) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741848423a2400916.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论