Search code examples
javascriptdomchild-nodes

Selecting a child node (DOM)


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>

Solution

  • 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>