How Can I Add Class On Active Li With Javascript Code
- Home
Solution 1:
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; }
<ulclass="nav nav-tabs"><li><ahref="#">Home</a></li><li><ahref="#">Menu 1</a></li><li><ahref="#">Menu 2</a></li><li><ahref="#">Menu 3</a></li></ul>
Solution 2:
if you have jquery
<ulclass="nav nav-tabs"><li><ahref="#">Home</a></li><li><ahref="#">Menu 1</a></li><li><ahref="#">Menu 2</a></li><li><ahref="#">Menu 3</a></li></ul><style>.active {background-color: #0f9;} </style><scripttype="text/javascript"> $("ul.nav.nav-tabs").on('click', 'li', function(){ $(this).siblings().removeClass('active'); $(this).addClass('active'); }); </script>
Vanilla JavaScript (ES6 where I tested, might work on ES5)
const elm = document.querySelector('ul'); elm.addEventListener('click', (el) => { const elActive = elm.querySelector('.active'); if (elActive) { elActive.removeAttribute('class'); } el.target.setAttribute('class', 'active'); });
Post a Comment for "How Can I Add Class On Active Li With Javascript Code"