简体   繁体   中英

How to remove the active class from first li-item while other one is active using JavaScript(!important))

I am working on an old site where only JavaScript codes are working. Problem is: the active class is working but while clicking on other "li", the li "Home" still remains active. Please suggest what other code need to be added in JS. Thanks in advance! The code are:

 function setActive() { aObj = document.getElementById('navmenu').getElementsByTagName('a'); for (i = 0; i < aObj.length; i++) { if (document.location.href.indexOf(aObj[i].href) >= 0) { aObj[i].className = 'active'; } } } window.onload = setActive; 
 <div id="navmenu"> <ul> <li><a href="/">Home</a> </li> <li><a href="/Home/Vision">Vision</a> </li> <li><a href="/Home/Career">Career</a> </li> </ul> </div> 

When you use indexOf() , you're testing whether aObj[i].href is anywhere in document.location.href , you're not testing whether it exactly matches the path. Since / is in /Home/Vision , that test succeeds. Try doing an exact match of document.location.pathname .

 function setActive() { aObj = document.getElementById('navmenu').getElementsByTagName('a'); for (i = 0; i < aObj.length; i++) { if (document.location.pathname == aObj[i].href) { aObj[i].className = 'active'; } } } window.onload = setActive; 
 <div id="navmenu"> <ul> <li><a href="/">Home</a> </li> <li><a href="/Home/Vision">Vision</a> </li> <li><a href="/Home/Career">Career</a> </li> </ul> </div> 

Check if the below link works with you.

http://jsfiddle.net/FnK9D/16/

function setActive(){aObj = document.getElementById('navmenu').getElementsByTagName('a');
    for (i = 0; i < aObj.length; i++) {
        if (document.location.href.indexOf(aObj[i].href) >= 0) {
            aObj[i].className = 'active';
         }
    }
}

window.onload = setActive;

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