53

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?

James Harzs
  • 1,853
  • 5
  • 21
  • 30

6 Answers6

55

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

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
37
 var mainDiv = document.getElementById('mainDiv');
 var x = mainDiv.children[0].children[1];

or

 var mainDiv = document.getElementById('mainDiv');
 var x = mainDiv.getElementsByTagName('div')[0].getElementsByTagName('div')[1];
Chao Zhang
  • 1,476
  • 2
  • 14
  • 25
17

I would go simply with just one line of vanilla code.

Works for any elements, is not limited to the tag names you have in the structure. But the number of elements and the hierarchy must be preserved.

var requiredDiv = document.getElementById('mainDiv').firstChild.firstChild.nextSibling;
TeeJay
  • 1,593
  • 3
  • 21
  • 33
11

I would pick jQuery and end up with something like this:

var getThis = $('#mainDiv > div:eq(0) > div:eq(1)');

Fiddle

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2
var mainDiv = document.getElementById('mainDiv');
var div = maindiv.getElementsByTagName('div')[2];//third div

http://jsfiddle.net/MGVw8/

Musa
  • 96,336
  • 17
  • 118
  • 137
0

You know there is querySelector now ?

console.log(
  mainDiv.querySelector(':nth-child(1) > :nth-child(2)'))
<div id="mainDiv">
  <div>
    <div></div>
    <div>come get me</div>
  </div>
  <!-- more stuff -->
</div>
vdegenne
  • 12,272
  • 14
  • 80
  • 106