Use document.querySelectorAll
to find the element which currently have the active
class, then you can remove that class.
function myFunction(e) {
var elems = document.querySelectorAll(".active");
[].forEach.call(elems, function(el) {
el.classList.remove("active");
});
e.target.className = "active";
}
JSFIDDLE
Instead of document.querySelectorAll
you can also use document.querySelector
function myFunction(e) {
var elems = document.querySelector(".active");
if(elems !==null){
elems.classList.remove("active");
}
e.target.className = "active";
}
JSFIDDLE 2
Edit
Instead of iterating through the entire collection you can select the element which have a class active
using document.queryselector. Also provide an id
to the ul so that you can target the specific element
function myFunction(e) {
if (document.querySelector('#navList a.active') !== null) {
document.querySelector('#navList a.active').classList.remove('active');
}
e.target.className = "active";
}
<style type="text/css">* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
header {
width: 100%;
height: auto;
max-width: 600px;
margin: 0 auto;
}
nav {
width: 100%;
height: 40px;
background-color: cornflowerblue;
}
ul {
list-style-type: none;
}
li {
display: inline-block;
}
a {
text-decoration: none;
padding: 8px 15px;
display: block;
text-transform: capitalize;
background-color: darkgray;
color: #fff;
}
a.active {
background-color: cornflowerblue;
}
<title>Navigation class Toggling</title>
<header>
<nav>
<ul onclick="myFunction(event)" id='navList'>
<li><a href="#">home</a></li>
<li><a href="#">about</a></li>
<li><a href="#">service</a></li>
<li><a href="#">profile</a></li>
<li><a href="#">portfolio</a></li>
<li><a href="#">contact</a></li>
</ul>
</nav>
</header>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…