Search code examples
javascripthtmlnestedhrefchildren

Javascript getting stripped href values from children elements (without jquery) assign active class


Idea: I Want to add class="active" to an li element, when specific link was clicked which is equal to the href and the url.

Problem: I can not select the href values which are nested inside a ul li. CSS might load the style to early. Note: The html gets injected with php.

Code:

window.onload = function () {
	
var curURL = window.location.href.split("/").pop(); //Outputs the current page url ex index.php

var linkNow = document.getElementsByClassName("topnav").getElementsByTagName("a").href;//Nesting this does not work but how can it be achieved?


//Loop check which curURL matches the href value, true->assign active class

for (var i = 0; i < link.length; i++) {
    if (curURL == linkNow[i]){
      linkNow.addClass("active");
      break;
    }
        
}

//As soon as the a element has the class="active" the navbar color will change
}
<ul class='topnav'>
  <li><a href='index.php'>Home</a></li>
  <li><a href='news.php'>News</a></li>
  <li><a href='showcase.php'>Showcase</a></li>
  <li class='icon'>
    <a href='javascript:void(0);' onclick='myFunction()'>&#9000;</a><!-- responsive icon-->
  </li>
</ul>


Solution

  • There are a number of ways to go about it, one is to use a selector to get the element directly, e.g.

    window.onload = function() {
      var href = 'index.php';
      var link = document.querySelector('a[href="' + href + '"]');
      link.parentNode.className = 'active';
    }
    .active {
      background-color: red;
    }
    <ul class='topnav'>
      <li><a href='index.php'>Home</a></li>
      <li><a href='news.php'>News</a></li>
      <li><a href='showcase.php'>Showcase</a></li>
    </ul>

    To be compatible with older browsers, you could also use a more general selector like:

    var links = document.querySelectorAll('ul a');
    

    or even:

    var links = document.links;
    

    which is compatible with pretty much every browser ever, then loop over them looking for the appropriate href value.