Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Iterating through a collection 2

Status
Not open for further replies.

Kalisto

Programmer
Feb 18, 2003
997
GB
I have a page that contains a number of nested <div> tags within a main <div>.

Is there any way of accessing the collection of div's that are within <maindiv> and iterating across the collection, rather than having to hard code them into my page, which reduces reusability!

K
 
There are a few ways you could do it. Examples ...

Code:
blah = document.getElementById( "maindiv" ).getElementsByTagName( "div" );
for ( var i=0; i < blah.length; i++ ) {

 ... etc ...

Code:
el = document.getElementById( "maindiv" );
for ( var i=0; i < el.childNodes.length; i++ ) {
if ( blah[ i ].tagName == "DIV" ) {

 ... etc ...

HTH.
 

Code:
var myDivs = document.getElementById('maindiv').getElementsByTagName('div');

for (var loop=0; loop<myDivs.length; loop++) {
   // do something here with myDivs[loop]
}

should work.

Hope this helps,
Dan


The answers you get are only as good as the information you give!

 
OK, to follow on, say I wish to toggle the visible attribute of these divs off, I would expect to use the following;

document.getElementById(myDivs[ loop ].id).style.visibility = "hidden";

but it doesnt work, myDivs[ loop ].id equates to [object], so what is the right syntaxt to access the name there, so I can use teh above code statement.

K
 

Use:

Code:
myDivs[loop].style.visibility = 'hidden';

since myDivs[loop] is a pointer to the element itself, not a string containing the id.

Hope this helps,
Dan


The answers you get are only as good as the information you give!

 

Sorry - I'd not read your post properly, and didn't see the ".id" bit.

Strange that it equates to an object, but anyway, the syntax given in my last post should work fine.

Dan


The answers you get are only as good as the information you give!

 
Thanks, I'd just arrived at that position when you replied !

I have more questions, but I'll scratch my head for a while before I shout again !

K
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top