简体   繁体   中英

how do you change a active class in html

i have a navigational bar at the side of my website but the problem is that when i change the tab in the navigational bar the active class does not change here is my code

 <!DOCTYPE html>
<html>
<body style="background-color:yellow">

<font color="red"><div align="center"><h1>About</h1></div></font>
<head>
<style>
body {
    margin: 0;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 25%;
    background-color: #875050;
    position: fixed;
    height: 100%;
    overflow: auto;
}

li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

li a.active {
    background-color: #4CAF50;
    color: white;
}

li a:hover:not(.active) {
    background-color: #555;
    color: white;
}
 </style>
</head>
<body>
<ul>
  <li><a class="active" href="prodject.htm">Home</a></li>
  <li><a href="prodject1.htm">News</a></li>
  <li><a href="prodject2.htm">Contact</a></li>
  <li><a href="prodject3.htm">About</a></li>
</ul>

</body>
</html>

and here is my java script code

$(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
        $(this).removeClass("active");
    }
    $(this).addClass("active");
});

is there any way to fix this

You don't have nav class in HTML

<ul class="nav">
   <li><a class="active" href="prodject.htm">Home</a></li>
</ul>

You don't need if , directly use selector with the method.

$(".nav li").click(function() {
    $(".nav li.active").removeClass("active");
    $(this).addClass("active");
});

OR,

$(".nav li").click(function() {
    $(this).siblings(".active").removeClass("active");
    $(this).addClass("active");
});

You don't have a nav class in your dom tree. Add to ul element class attribute with nav value:

<ul class="nav"></ul>

make sure you also have the class attribute for those a tags but also maybe you target the a tag and not nav li

 $("a").click(function() { $(this).siblings("active").removeClass("active"); $(this).addClass("active"); }); 

You do not have added nav class to ul tag use this code <ul class="nav"></ul> and make changes in jquery use below jquery code.

$(".nav li").click(function() {
    $(".nav li.active").removeClass("active");
    $(this).addClass("active");
});

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