treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Add a class to the parent li of .active using raw javascript

  • Hi,

    I want to add a class name to the parent li item of li a.active


    <div id="nav2">
    <ul>
    <li></li>
    <li></li><!-- add class here -->
    <ul>
    <li></li>
    <li><a class="active"></a></li>
    </ul>
    <li></li>
    </ul>
    </div>

    I need to use raw javascript but I'm just starting out with javascript and this is taking me forever to work out.


    Any help would be much appreciated.

    Steve
  • Well try

    var navlinks = document.getElementById('nav2').getElementsByTagName('a');
    for (var i = 0; i < navlinks.length; i++) {
    if(navlinks[i].className == 'active'){
    navlinks[i].parentNode.parentNode.parentNode.className = 'YOUR CLASS';
    }
    }


    Hope it works, have no idea when i did somthing like that without jquery the last time ^^
  • Cheers Sirlon,

    That code was what i almost got myself, I must be learning a bit.

    Thanks