homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

Looping through all the descendants of an element

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

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)

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)

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.

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved