Reputation: 427
How to make only the clicked element show the background color through javascript, and the rest of the elements disappear? Since I'm just learning the language, I don't quite know how to fix my code to achieve this effect?
thank you all.
function addStyle() {
this.style.background = "blue";
}
var el = document.querySelectorAll('li');
for (var i = 0; i < el.length; i++) {
el[i].addEventListener('click', addStyle);
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
Upvotes: 0
Views: 30
Reputation: 63550
As a corollary to David's answer you might also consider using event delegation. Instead of attaching multiple listeners to multiple elements add one to the containing element (the list) and catch events from its child elements as they "bubble up" the DOM. You can then check that the element is a list item, remove all the classes from the other list items, and set the class for the clicked child element.
const list = document.querySelector('ul');
const items = list.querySelectorAll('li');
list.addEventListener('click', handleClick);
function handleClick(e) {
if (e.target.matches('li')) {
items.forEach(item => item.classList.remove('blue'));
e.target.classList.add('blue');
}
}
.blue { background-color: lightblue; }
li:hover:not(.blue) { cursor: pointer; background-color: #efefef; }
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
Upvotes: 1
Reputation: 218960
Before setting the background to blue, unset all of the backgrounds:
function addStyle() {
// unset all backgrounds
for (var i = 0; i < el.length; i++) {
el[i].style.background = "unset";
}
// set this one to blue
this.style.background = "blue";
}
var el = document.querySelectorAll('li');
for (var i = 0; i < el.length; i++) {
el[i].addEventListener('click', addStyle);
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
Upvotes: 1