I want to have an event that strikes through the text on my li
My HTML
<!DOCTYPE html>
<html>
<head>
<title>Javascript + DOM</title>
<link rel="stylesheet" type="text/css" href="5.3 style.css">
</head>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
<li class="bold red" random="23">Notebook</li>
<li class="bold red">Jello</li>
<li class="bold red">Spinach</li>
<li class="bold red">Rice</li>
<li class="bold red">Birthday Cake</li>
<li class="bold red">Candles</li>
</ul>
<script type="text/javascript" src="5.2 script.js"></script>
</body>
</html>
My CSS
.done {
text-decoration: line-through;
}
My JS
var list = document.getElementsByTagName("li");
list.addEventListener("click", function(e){
list.classList.toggle("done");
})
I have tried:
var list = document.querySelector("li");
it only gets the first li obviously, so I tried
querySelectorAll it isn't working it tells me the error:
Uncaught TypeError: Cannot read property 'toggle' of undefined"
You need to attach click listener to all the li elements which you get from document.getElementsByTagName("li"); as the getElementsByTagName() returns you the list of elements with that tag and you need to assign the listener individually to each tag which was missing in your code and hence, error was showing up.
var list = document.getElementsByTagName("li");
for(var i=0; i<list.length; i++){
list[i].addEventListener("click", liClick);
}
function liClick(){
this.classList.toggle("done");
}
.done {
text-decoration: line-through;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript + DOM</title>
<link rel="stylesheet" type="text/css" href="5.3 style.css">
</head>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
<li class="bold red" random="23">Notebook</li>
<li class="bold red">Jello</li>
<li class="bold red">Spinach</li>
<li class="bold red">Rice</li>
<li class="bold red">Birthday Cake</li>
<li class="bold red">Candles</li>
</ul>
<script type="text/javascript" src="5.2 script.js"></script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With