Theodore Steiner Theodore Steiner - 1 year ago 72
HTML Question

Targeting Elements on Click

I found a small "To Do List" exercise in which the user clicks on a list item and a JS function changes the background of what was clicked to a different color, using an

Now I understand there are easier ways to do this but I wanted to experiment with passing an event that a function "looks for" and then activates a particular feature but I'm a little stuck.

In my example, instead of a list, the function looks for a P element. I can get the following to work if I search for == "P", however I wanted to try looking by the ID. When I change the function to read === "text" however, it does not work. What am I missing?




<div id="list2">
<p id="text">Text</p>
<p id="text">Text</p>
<p id="text">Text</p>


var list = document.querySelector("ul");

list.onclick = function(e)
if( === "LI")

var list2 = document.getElementById("list2");

list2.onclick = function(e)
if( === "text")

Ted Ted
Answer Source

Two main issues:

1) You cannot have elements with the same id. Ids are unique to elements, and CANNOT be repeated. Classes on the other hand, you can have multiple of.

2) Addressing your main question, id should be in lowercase, rather than uppercase. So changing your code to : does the trick.

Let me know if you have any further questions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download