skaterdav85 Posted January 2, 2011 Share Posted January 2, 2011 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 More sharing options...
jeffman Posted January 2, 2011 Share Posted January 2, 2011 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 More sharing options...
skaterdav85 Posted January 3, 2011 Author Share Posted January 3, 2011 oh ok, thanks DD. that makes perfect sense actually. i've always tried to avoid recursive functions since they make my head spin haha Link to comment Share on other sites More sharing options...
jeffman Posted January 3, 2011 Share Posted January 3, 2011 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 More sharing options...
skaterdav85 Posted January 3, 2011 Author Share Posted January 3, 2011 good point. I can see why DOM traversal in raw JS is much more challenging than using a library. I was just working with this example for the sake of learning it in raw JS. Link to comment Share on other sites More sharing options...
jeffman Posted January 3, 2011 Share Posted January 3, 2011 That's a professional attitude. Anyway, it's really not that hard when you get a feel for it. FWIW, you might find this tutorial from Sophox useful, and maybe this one too. Both of them use the sort of looping I was hinting at. Link to comment Share on other sites More sharing options...
skaterdav85 Posted January 3, 2011 Author Share Posted January 3, 2011 those are great tutorials. is that your site? Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.