View Full Version : Traverse DIVs using getElementById
JohnTirone
01-09-2003, 08:34 PM
If I have the following in my document
<DIV id="leftdiv">
<DIV id="innerDiv1">
<DIV id="innerDiv1a">
<input id="input1">
</DIV>
</DIV>
</DIV>
How would I get a reference to the input1 element using "getElementById"?
I'm trying (document.getElementById("leftdiv")).document. ...
thank you!:confused:
Please post this in a more relevant forum next time. I had to move it here.
Anyway:
document.getElementById('leftDiv').firstChild.firstChild.firstChild
Or since you have them all id'ed:
document.getElementById('innerDiv1a').firstChild
Adam20002
01-10-2003, 11:48 AM
I was wondering, can't you just say
document.getElementById("input1")
Adam
JohnTirone
01-10-2003, 02:13 PM
Ok, my example was too simple.
I REALLY WANT TO KNOW HOW TO: "getElementById", use that element's document to "getElementById" ... and so on.
Is there a way to do that?
FYI, I will know how many time's that I'll need to repeat the sequence.
NOTE: My innerDiv1, innerDiv2, ... are distinct, but their contents innerDiv1a, input1 ARE NOT! They get repeated as in the following example:
<DIV id="leftdiv">
<DIV id="innerDiv1">
<DIV id="innerDiv1a">
<input id="input1">
</DIV>
</DIV>
<DIV id="innerDiv2">
<DIV id="innerDiv1a">
<input id="input1"> THIS IS THE ONE I WANT
</DIV>
</DIV>
<DIV id="innerDiv3">
<DIV id="innerDiv1a">
<input id="input1">
</DIV>
</DIV>
</DIV>
THANKS AGAIN!!!
:confused:
Bosko
01-10-2003, 03:51 PM
You can't have multiple elements with the same id.
I do not really understand what you want,but you should try using getElementsByTagName.
Originally posted by Adam20002
I was wondering, can't you just say
document.getElementById("input1")
Adam
LOL! I didn't notice the <input/> *had* an id. :D
brothercake
01-10-2003, 05:36 PM
getElementsByTagName could be the one, and with a bit of scripting you can create your own getElementsByClassName function, which I find very useful, eg (for divs):
<script>
var divAry=new Array;
var i=0;
function getElementsByClassName(cName) {
var divCollection = document.getElementsByTagName("div");
var divLen = divCollection.length;
for(i=0;i<divLen;i++){
if(divCollection[i].className==cName) { divAry[i]=divCollection[i]; i++; }
}
}
</script>
<a href="javascript:getElementsByClassName('small');alert(divAry);">getElementsByClassName</a>
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.