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?
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];
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With