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
Add a ment  | 

1 Answer 1

Reset to default 6

Use 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