Theodore Steiner
Theodore Steiner

Reputation: 1615

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 e.target.tagName.

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 e.target.tagName == "P", however I wanted to try looking by the ID. When I change the function to read e.target.Id === "text" however, it does not work. What am I missing?

Code:

HTML:

<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>

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

JS:

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

list.onclick = function(e)
{
if(e.target.tagName === "LI")
{
    e.target.classList.toggle("done");
}
};


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

list2.onclick = function(e)
{
if(e.target.Id === "text")
{
    e.target.classList.toggle("done");
}
};

Upvotes: 0

Views: 171

Answers (2)

Ted
Ted

Reputation: 756

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 : e.target.id does the trick.

Let me know if you have any further questions.

Upvotes: 1

jonju
jonju

Reputation: 2736

The issue is in e.target.Id. It should id(lower case) since javascript is a case-sensitive language.

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

list.onclick = function(e)
{
if(e.target.tagName === "LI")
{
    e.target.classList.toggle("done");
}
};


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

list2.onclick = function(e)
{
if(e.target.id === "text")
{
    e.target.classList.toggle("done");
}
};
.done{
  background-color:greenyellow;
}
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>

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

Upvotes: 0

Related Questions