Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Looping through all the descendants of an element



12:54 am on Apr 28, 2009 (gmt 0)

5+ Year Member

any idea why this isn't working. I'm trying to loop through all the descendants of all the elements with a name of "dad_object". but every time i run it it tells me d is not defined. am i using the .elements property wrong?

function indexObject() {
var e = document.getElementsByName("dad_object");

for (i = 0; i < e.length; i++) {
e[i].setAttribute("dadObjectIndex", i);
e[i].onmouseover = overObjectEv ;

var d = e[i].elements ;
for (var l = 0; l < d.length; l++) {
if (d[l].getAttribute("dadexclude") == "1") {
d[l].onmouseover = overExcludeObjectEv ;


1:55 am on Apr 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

Think elements is only property of forms ?

Try childNodes instead, note nodes may be other than elements


11:37 am on Apr 28, 2009 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member

And just to throw a spanner in the works, eventually you will get to the end of the tree and there will be no descendants.

In this case, e[i].childNodes will not exist. If you get this problem try this:

var d = e[i].childNodes  new Array();

I'm not sure without testing but that should create an empty array if there is no childNodes property, so the second loop won't run as the length will be 0.

Also, this function will only go 1 level deep, is that what you want? e.g.:

<div name='dad_object'> 
<p>Text <a>Link</a></p>

In this example it would pick up the <p> but not the <a>.

It is possible (and correct) for more than one object to have the same name. Think radio buttons. So, the getObjectsByName function returns a list. If there is only 1 object it still returns a list but with only 1 element.

I realise this is your own code, and you're not silly enough to break it, but for correctness you should take it into account. Try this:

var e = document.getElementsByName("dad_object")[0];

See the [0] on the end? This ensures you will always get the first element.


Featured Threads

Hot Threads This Week

Hot Threads This Month