简体   繁体   中英

How can I add class on active li with JavaScript code

<ul class="nav nav-tabs">
    <li onclick="this.className='active'"><a href="#">Home</a></li>
    <li onclick="this.className='active'"><a href="#">Menu 1</a></li>
    <li onclick="this.className='active'"><a href="#">Menu 2</a></li>
    <li onclick="this.className='active'"><a href="#">Menu 3</a></li>
</ul>

How can I add active class on li tag with JavaScript. Here I am try to do it. It is working but not properly. I am doing for tabs here.

As per the comments, I guess you are expecting this:

 var a = document.querySelectorAll(".nav li a"); for (var i = 0, length = a.length; i < length; i++) { a[i].onclick = function() { var b = document.querySelector(".nav li.active"); if (b) b.classList.remove("active"); this.parentNode.classList.add('active'); }; } 
 .active { background-color: #0f9; } 
 <ul class="nav nav-tabs"> <li><a href="#">Home</a> </li> <li><a href="#">Menu 1</a> </li> <li><a href="#">Menu 2</a> </li> <li><a href="#">Menu 3</a> </li> </ul> 

if you have jquery

<ul class="nav nav-tabs">
  <li><a href="#">Home</a></li>
  <li><a href="#">Menu 1</a></li>
  <li><a href="#">Menu 2</a></li>
  <li><a href="#">Menu 3</a></li>
</ul>

<style>
 .active {background-color: #0f9;}
</style>
<script type="text/javascript">
$("ul.nav.nav-tabs").on('click', 'li', function(){
  $(this).siblings().removeClass('active');
  $(this).addClass('active');
});
</script>

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