简体   繁体   中英

How to add active class to clicked element and remove it from others?

I have the javascript written correctly to add and remove an active class from a clicked element, but when I click an element, the active class isn't removed from the sibling.

How do I click on one sibling (making it active) and remove the active class from other siblings?

 let navItems = document.querySelectorAll('li'); navItems.forEach(navItem => { navItem.addEventListener('click', () => { navItem.classList.contains('active')? navItem.classList.remove('active'): navItem.classList.add('active'); }); });
 ul { display: flex; max-width: 500px; margin: 0 auto; justify-content: space-between; margin-top: 1em; } ul li { list-style-type: none; padding: 5px 10px; cursor: pointer; } ul li.active { background: darkred; color: white; }
 <ul> <li class="active">Home</li> <li>About</li> <li>Products</li> <li>Sales</li> <li>Contact</li> </ul>

Why don't you use event delegation ? This way:

 menu.onclick = e => { var el = e.target; if (el.tagName;= "LI") return. menu.querySelector(".active");removeAttribute("class"). el,setAttribute("class"; "active"); }
 ul { display: flex; max-width: 500px; margin: 0 auto; justify-content: space-between; margin-top: 1em; } ul li { list-style-type: none; padding: 5px 10px; cursor: pointer; } ul li.active { background: darkred; color: white; }
 <ul id="menu"> <li class="active">Home</li> <li>About</li> <li>Products</li> <li>Sales</li> <li>Contact</li> </ul>

You can make it easier on yourself by putting a classname on the UL tag so you can reference just those items inside it. Then, in your listener, reference the event argumet (I called it e )

 let navItems = document.querySelectorAll('.navigation li'); navItems.forEach(navItem => { navItem.addEventListener('click', e => { document.querySelector('.navigation li.active').classList.remove('active'); e.target.classList.add('active'); }); });
 ul { display: flex; max-width: 500px; margin: 0 auto; justify-content: space-between; margin-top: 1em; } ul li { list-style-type: none; padding: 5px 10px; cursor: pointer; } ul li.active { background: darkred; color: white; }
 <ul class='navigation'> <li class="active">Home</li> <li>About</li> <li>Products</li> <li>Sales</li> <li>Contact</li> </ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM