Jump to content

getting the nodeName recursively


skaterdav85

Recommended Posts

I started playing around with the DOM traversing properties but I am having trouble using the nextSibling property. I am trying to use a recursive function to get the nextSibling of the p element with an id of 'hello'. I want the function to return the nodeName of the div with an id of 'siblingDiv'. It is returning undefined though and not sure why. Check out the link below. You can modify the JS within the page and save it too. Pretty neat tool if you haven't used it =)http://jsbin.com/osugi4/6/edit

Link to comment
Share on other sites

I think you'd find this easier if you used a loop instead of a recursive function. In any case, the trouble here is that you need to set up a chain of return values. I mean, you need to return the return value of getSibling with every iteration. Otherwise, the final iteration will return the nodeName, but the iteration that called it doesn't do anything with the result, and so on and on back to the initial iteration, which means your return value is empty.So, that's the convoluted explanation. The answer is simply this:return getSibling(elem.nextSibling);

Link to comment
Share on other sites

I should have added: this could be a useful utility that you port to a lot of apps. To make it really robust, you'll need to check that an element actually HAS a nextSibling before you start checking its properties.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...