Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

parentNode vs parentElement

In the 'Traversing the DOM' course, parentNode is used to select a parent element. I was wondering why parentElement would not be used, since parentNode might not return an HTML element. Is it because of browser support? Whan I used parentElement in the final practice, it seemed to work fine. Thanks.

2 Answers

Steven Parker
Steven Parker
242,796 Points

The parentNode method will always return the parent, but parentElement will return null if the parent happens to be something other than an element. So unless you're prepared to test for a null return you probably don't want parentElement.

Also, for practical purposes the parent node of an element will nearly always be an element, unless it's the document object itself.

Thanks for this clear response.