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 trialMurilo de Melo
14,456 PointsI'm not sure I understood parentNode. Why not to apply event handler directly the parent element or item?
I'm not understand the need of parentNode as a feature that provides a functionality that could be reached with a direct event handler on the parent element, without parentNode.
1 Answer
James Croxford
12,723 PointsFrom what I've read, parentNode becomes very useful when you have a complex JavaScript document, or when faced with targeting a particular HTML element for which you don't know what the parent element is (or perhaps you don't have or know any ID or class names). Perhaps you're writing JavaScript for a website, and you only have part of the HTML file as the rest is being created, or ID & class names for the parent element (in this case <ul>) may be added/removed/changed down the line. Even if they are, because we are utilising parentNode, we can be sure that we target the correct <li> tag when the button is clicked, and then from there target <ul>. This callback function we are using will not be reliant on specific ID tags or class names.
Remember too that for app.js, we are separating out the text of the list item from the functionality (removing it from the list). To make it clear to the user, we are making a specific 'remove' button element inside each list item, rather than expecting the user to work out that they need to click the text itself to remove it (think of accessibility for visually impaired users for example- their browser will be able to read the text on the remove button, providing context and understanding of the features of the webapge).
So the event handler has to be applied to the <button>, as this is where we want the event to be registered- the button itself, not the entirety of the containing <li>. It's then quite simple to use parentNode to move up the DOM tree, find the <li> which contains the <button>, then find the <ul> that holds the <li>. We can then run removeChild, knowing that we have created temporary variables that exist in the scope of the callback function to pass to it. All of this is without needing to know any specifics about the individual list item or its parent element, <ul>.