简体   繁体   中英

How to have default and remove class on Ul li using vanilla JavaScript?

I have two ul with the same class, the concept I tried to achieve is when clicking the active li should have border color change. I have succeeded in that, the concept I need is I want to have the default same border color present on first ul li, and if I click other it should get removed and color should apply on clicked one. The code I have tried so far.

Any help will be appreciated !!

 var x = document.querySelectorAll('.random-value li'); for (var i = 0; i < x.length; i++) { x[i].addEventListener("click", function() { var selectedEl = document.querySelector(".selected"); if (selectedEl) { selectedEl.classList.remove("selected"); } this.classList.add("selected"); }, false); };
 .random-value li{ margin: 0 0 15px 0; border: 1px solid green; padding: 15px 26px; } .random-value .selected{ border: 1px solid red; }
 <ul id="first" class="random-value"> <li>200 </li> <li>2010 </li> <li>2100 </li> <li>2030 </li> </ul>

I think this is what you are looking for,

 //Making first option as Highlighted document.querySelectorAll('.random-value li')[0].classList.add("selected"); var x = document.querySelectorAll('.random-value li'); for (var i = 0; i < x.length; i++) { x[i].addEventListener("click", function() { var selectedEl = document.querySelector(".selected"); if (selectedEl) { selectedEl.classList.remove("selected"); } this.classList.add("selected"); }, false); };
 .random-value li{ margin: 0 0 15px 0; border: 1px solid green; padding: 15px 26px; } .random-value .selected{ border: 1px solid red; }
 <ul id="first" class="random-value"> <li>200 </li> <li>2010 </li> <li>2100 </li> <li>2030 </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