JavaScript JavaScript and the DOM Responding to User Interaction Event Delegation

Sarah Yasi
Sarah Yasi
3,621 Points

Not sure why this code isn't working.

I can't seem to figure out why the input element isn't being targeted properly.

app.js
let section = document.getElementsByTagName('section')[0];

section.addEventListener('click', (e) => {
  if (event.target.targetName = 'INPUT') {
      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>

2 Answers

KRIS NIKOLAISEN
KRIS NIKOLAISEN
53,478 Points

Some hints:

  • The property you are looking for is tagName
  • You are using an assignment operator in your if condition. To make a comparison use ==.
Juan Lopez
Juan Lopez
Treehouse Project Reviewer

Hey Sarah good job on writing your if statement. So there are a couple of minor details that need changing to pass the challenge.

if (event.target.targetName = 'INPUT') {

So starting off it seems as though there might be a small mistake as to the property you were trying to access from the event.target looks as though you might have meant tagName instead of targetName.

If you do a console.dir(event.target) and open your Chrome Dev Tools you'll be able to see what properties are accessible from event.target.

Secondly, keep in mind the = will try and assign a value rather than check a value. With that being said you'll want to use the === to check if the event.target.tagName is equal to INPUT like so

section.addEventListener('click', (e) => {
  if (e.target.tagName === 'INPUT') {
  e.target.style.backgroundColor = 'rgb(255, 255, 0)';
  }
});