Add/Delete class to <li> with Javascript when you are on specific div.

15,934

Solution 1

You will use the node tree for setting attribute. What i mean

var node = document.getElementById("dividname").getElementsByTagName("li")[i];
node.setAttribute("class", "classname");

for deleting the class just use above without any value

node.setAttribute("class", "");

Solution 2

a simplest solution in jquery that comes to my mind would be something like:

$('.menu-link').click(function(){
 var divId = $(this).attr("href");
 $('.page-div').removeClass("special-class");
 $(divId).addClass("special-class");
});

please note that .menu-link is a class for your <a> inside <li> and .page-div is a class for divs with ids page1, page2 etc.

Share:
15,934
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    I open this thread to ask your help with JavaScript.

    My website is divided vertically into four main div.

    <div id="homepage"> Content </ div>
    <div id="page1"> Content </ div>
    <div id="page2"> Content </ div>
    <div id="page3"> Content </ div>
    <div id="page4"> Content </ div>
    

    On the right of page there is navigation menu, div position: fixed.

    <div id="nav">
    <ul>
    <li> <a href="#homepage"> Homepage </ a> </ li>
    <li> <a href="#page1"> Page1 </ a> </ li>
    <li> <a href="#page2"> Page2 </ a> </ li>
    <li> <a href="#page3"> Page3 </ a> </ li>
    <li> <a href="#page4"> page4 </ a> </ li>
    </ ul>
    </ div>
    

    I wish that when you are in a div container (page1 or page2 etc) is added to a class corresponding menu item.

    And 'possible to do this with javascript? Thanks in advance

  • Admin
    Admin about 12 years
    But I would not have the event only if you click on the menu. The menu items should light up even if I use the scroll bar with the mouse.