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 JavaScript and the DOM (Retiring) Traversing the DOM Sibling Traversal

for loop ?

I keep getting it doesnt effect all the 'p' do I need to create a for loop or something else ?

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

list.addEventListener('click', function(e) {
  if (e.target.tagName == 'BUTTON') {
    let p = document.querySelector('p')
    let highLight = document.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>

I have tried solutions i just deleted them

3 Answers

querySelector() selects the first element that fits the condition.

you want to use querySelectorAll() to select all of the elements that fit the condition.

i had originally had that there but i had deleted it , but ill add it back , but the main issue was how am i suppose to add the highlight class to the p ?

hey, was gonna lay this one for you but i had a feeling it was already in a previous community post and it was. Check it out here: https://teamtreehouse.com/community/can-any-one-please-help-me-solve-this-challenge

thank you

let highLight = document.className='highlight';

you wanted to set the className of p, but you actually wrote to set the classname of document.

    let p = document.querySelectorAll('p');
    p.forEach(element => element.className = 'highlight');

in p you should have an array with all p elements, so now you should be able to loop over those and set the className.

anyway, the challenge is to actually highlight only the one that is the direct sibling of the button being pressed. So this code will not do what the challenge asked.

For solving the challenge, you might want let p = e.target.previousElementSibling;

oh ok ok much appreciated