3

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>
Jordan Davis
  • 1,485
  • 7
  • 21
  • 40
MartinDK81
  • 343
  • 2
  • 8
  • 16
  • 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 Sep 29 '15 at 18:39

1 Answers1

5

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>
Jordan Davis
  • 1,485
  • 7
  • 21
  • 40
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53