I've been working on creating a navigation menu and I've completed the HTML and CSS part. However, when it comes to implementing Javascript, I'm facing an issue. I can add a class to an element, but I'm struggling to remove the class from the remaining elements. Can someone please assist me with this?
Here's my code:
<!DOCTYPE html>
<html>
<head>
<title>Toggle Navigation Class</title>
<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;
}
</style>
</head>
<body>
<header>
<nav>
<ul onclick="myFunction(event)">
<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>
<script type="text/javascript">
function myFunction(e) {
e.target.className = "active";
}
</script>
</body>
</html>
Here is the link to my Codepen