Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) Traversing the DOM Sibling Traversal

previous sibling

Can someone walk me through this, please? I'm having a hard time understanding what happening here how could I add a class of highlight to a <p> element that's an immediate previous sibling of the button is clicked.

var list = document.getElementsByTagName('ul')[0];

list.addEventListener('click', function(e) {
  if (e.target.tagName == 'BUTTON') {
if(e.target.previousElementSibling.tagName && e.target.previousElementSibling.tagName === "P"){
<!DOCTYPE html>
        <title>JavaScript and the DOM</title>
    <link rel="stylesheet" href="style.css" />
            <h1>Making a Webpage Interactive</h1>
            <p>Things to Learn</p>
                <li><p>Element Selection</p><button>Highlight</button></li>
                <li><p>Event Listening</p><button>Highlight</button></li>
                <li><p>DOM Traversal</p><button>Highlight</button></li>
        <script src="app.js"></script>

1 Answer

Steven Parker
Steven Parker
218,692 Points

You're close, here's a few hints:

  • the instructions say to add a class of 'highlight' to the paragraph (not 'highlight‍ed')
  • the conditional expression has a spurious term in it (before and including the &&)
  • the instructions say you can expect the previous sibling to be a paragraph, you don't need to test it at all

Actually, the instructions don't say anything about what to expect for the previous element's sibling. In this challenge, you can omit the testing for the 'p' tag and it will work because the html has only p elements as immediate previous siblings for the buttons, but that doesn't mean that it would always work that way, so given the instructions "to add a class of highlight to a <p> element that's an immediate previous sibling of the button being clicked", I would also have done it the way Leila did (without the other issues mentioned, of course).

Steven Parker
Steven Parker
218,692 Points

The instructions say to add a class "to a <p> element that's an immediate previous sibling...". So they're telling you that the previous sibling (of this element, the button) will be a paragraph.