Selecting second children of first div children in javascript

James Harzs picture James Harzs · Aug 21, 2012 · Viewed 83.7k times · Source

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?

Answer

nnnnnn picture nnnnnn · Aug 21, 2012

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).