JavaScript JavaScript and the DOM Traversing the DOM Sibling Traversal

Julianna Kahn
Julianna Kahn
20,699 Points

My understanding is that the paragraph would be the previousElementSibling to the button?

Am I defining p correctly?

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

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

3 Answers

Steven Parker
Steven Parker
173,784 Points

You have the right idea, and you're doing the right thing with "p".

But the button is not "e.target.tagName", but simply "e.target".

Jason Anders
MOD
Jason Anders
Treehouse Moderator 144,810 Points

HI Julianna Kahn

For this one, I'm going to direct to a very well explained answer provided by Antony Pesantez in this older post.

Keep Coding! :) :dizzy:

Julianna Kahn
Julianna Kahn
20,699 Points

That is helpful, thank you.

Julianna Kahn
Julianna Kahn
20,699 Points

That makes a lot of sense, thank you.