Search code examples
javascripthtmlparent-childgetelementbyid

Selecting second children of first div children in javascript


I have an html that look something like this:

<div id="mainDiv"> <-- I have this
    <div>
        <div></div>
        <div></div> <-- I need to get this
    </div>
    <span></span>
    <more stuff />
</div>

i am using:

var mainDiv = document.getElementById('mainDiv');

because I need that div in a var, but i also need to get that second div on the first div inside mainDiv into a variable.

How could I do it in a simple cross-browser way?


Solution

  • Assuming that structure is static you can do this:

    var mainDiv = document.getElementById('mainDiv'),
        childDiv = mainDiv.getElementsByTagName('div')[0],
        requiredDiv = childDiv.getElementsByTagName('div')[1];
    

    Further reading: .getElementsByTagName() (from MDN).