JavaScript JavaScript and the DOM Responding to User Interaction Event Delegation

Not sure where i'm messing up. I was able to get the input only fields to have a background of yellow.

let section = document.getElementsByTagName('input');

for (let i = 0; i < section.length; i += 1) { section[i].addEventListener('click', (e) => { e.target.style.backgroundColor = 'rgb(255, 255, 0)'; }); };

app.js
let section = document.getElementsByTagName('input');

for (let i = 0; i < section.length; i += 1) {
  section[i].addEventListener('click', (e) => {
    e.target.style.backgroundColor = 'rgb(255, 255, 0)';
  });
};
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>JavaScript is an exciting language that you can use to power web servers, create desktop programs, and even control robots. But JavaScript got its start in the browser way back in 1995.</p>
            <hr>
            <p>Things to Learn</p>
            <ul>
                <li>Item One: <input type="text"></li>
                <li>Item Two: <input type="text"></li>
                <li>Item Three: <input type="text"></li>
                <li>Item Four: <input type="text"></li>
            </ul>
            <button>Save</button>
        </section>
        <script src="app.js"></script>
    </body>
</html>

3 Answers

I was able to see where i made the mistake. https://teamtreehouse.com/community/event-delegation-challenge

Gergely Bocz
MOD
Gergely Bocz
Treehouse Moderator 13,397 Points

Hi Tim Marsh !

The challenges asks you, to add a conditional that checks if the clicked element is an input field, and only if it's an input should it be turned yellow upon being clicked on!

What you are doing right now, is cycling through each of the section elements (with no point as there is only 1), and adding an eventlistener to each and every one of them. This isn't what this code challenge is about.

So the point is that you should add an if condition to the original code!

Try it on your own, and see if you can make it work! If not, write a comment and I'll help!

Good luck, Gergő

Thank you. I was able to get the desired result, but I don't think I'm still getting this answer correct because of what the challenge wants. I definitely have this course to go back over a 2nd time around.

let section = document.getElementsByTagName('input');

for (let i = 0; i < section.length; i += 1) {
  section[i].addEventListener('click', (e) => {
    e.target.style.backgroundColor = 'rgb(255, 255, 0)';
  });
}