JavaScript JavaScript and the DOM Responding to User Interaction Event Delegation

Fernando Jimenez
PRO
Fernando Jimenez
Pro Student 5,955 Points

Stuck with a simple Javascript code.

How come I am not just selecting the .li elements on app.js? what am I missing?

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>
app.js
let section = document.getElementsByTagName('section')[0];
section.addEventListener('click', (e) => {
  if(e.target.tagName == "LI"){
  e.target.style.backgroundColor = 'rgb(255, 255, 0)';}
  else{null}
});

3 Answers

Steven Parker
Steven Parker
163,562 Points

Your click handler does seem to be selecting the list items, as can be seen by them changing color when you click on them. Other section elements, such as the heading an paragraphs, are not affected.

However, the instructions say, "ensure that the text input elements are the only children that trigger the background-changing behavior..." So you should filter those instead of the list items.

Fernando Jimenez
PRO
Fernando Jimenez
Pro Student 5,955 Points

Well, when I click on check work it says: " Bummer: Make sure you are filtering out the right elements. "

These are the instructions: In the listener that has been added to the section element, ensure that the text input elements are the only children that trigger the background-changing behavior.

Steven Parker
Steven Parker
163,562 Points

Oops, I guess we both overlooked part of the instructions at first glance. I've revised my answer.

Pawel Ellwart
Pawel Ellwart
9,524 Points

Hi Fernando,

I also spent a lot of time on this and thought that it should work, there is one small detail that I think is not discussed during the course. tagName returns an element's value in capitalized letters so when you put "input" after "==" in if condition it has to be capitalized: "INPUT" , otherwise it won't work. That's also why during the course "LI" was capitalized.