Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting second children of first div children in javascript [duplicate]

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?

like image 707
James Harzs Avatar asked Aug 21 '12 03:08

James Harzs


2 Answers

 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]; 
like image 22
Chao Zhang Avatar answered Oct 05 '22 21:10

Chao Zhang


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

like image 87
nnnnnn Avatar answered Oct 05 '22 23:10

nnnnnn