Can someone please help me with a function to hide a list element, one by one, when clicking on it? I only got it to work but for one single element, I am not sure how it would go for all of them.
Suppose I have a list of 5 elements. When i click on element 1, it dissapears. If I click on element two, it also dissapears and so on.
I would like it to do on javascript vanilla only
This is that I’ve tried so far:
<!DOCTYPE html> <html> <body> <ul> <li id ="id1" onclick="document.getElementById('id1').style.visibility='hidden'">Coffee</li> <li class ="id1" onclick="document.getElementById('id1').style.visibility='hidden'">Coffee 2</li> <li class ="id1" onclick="document.getElementById('id1').style.visibility='hidden'">Coffee 3</li> </ul> </body> </html>
Advertisement
Answer
You can simply do this by passing event
parameter into a click handler function.
When you define your html like this onclick="onListItemClick(event)"
, Javascript automatically sends the event
object into your function.
Event
object has many properties inside of it. But all you are concerned with is the event.target
which is the element that you clicked on.
Then you can easily manipulate any part of that html element.
function onListItemClick(event) { event.target.style.visibility = 'hidden'; }
<!DOCTYPE html> <html> <body> <ul> <li onclick="onListItemClick(event)">Coffee 1</li> <li onclick="onListItemClick(event)">Coffee 2</li> <li onclick="onListItemClick(event)">Coffee 3</li> </ul> </body> </html>