Enable the menu link after loading the page

Asked

Viewed 28 times

-2

I need to make a comparison of the page I am loading with all elements of my tag a . so that finding the element he applies stylization. Someone can help me with this mistake?

window.onload =function(){
    
  var menu = document.getElementById('menu');
  var lista = document.getElementById('lista');
  var link = document.getElementsByTagName('a');
  var url_atual = window.location.href;
  
  for (i=0; i<link.length; i++ ){ //tira toda formatação da tag "a"
    link[i].style.backgroundColor = "";
    link[i].style.color = "";
  }
  menu.style.backgroundColor = "#ff0000"; // altera o fundo
  menu.style.color = "#ffffff"; // altera a cor

}
<head>
</head>
<body id="menu">
  <ul id="lista">
     <li><a href="index.html">Home</a></li>
     <li><a href="#">Fotos</a></li>
     <li><a href="#" >Agenda</a></li>
     <li><a href="#" >Contato</a></li>
  </ul>
</body>

  • Can you add an executable example? I don’t quite understand what you want

  • @Douglas Teles, from what I understand the goal is for the anchor element to appear in a different style if the address to which the anchor corresponds is the page address.

  • What comparison do you want to make? The question does not say.

1 answer

-1

Samuel see if that’s what you need:

window.onload =function(){
    var lista = document.getElementById('lista');
    var link = document.querySelectorAll('#lista a');
    var url_atual = window.location.href;

    for (i=0; i<link.length; i++ ){ 
        if(url_atual == link[i].href){
            link[i].style.backgroundColor = "#ff0000";
            link[i].style.color = "#ffffff"; 
        }else{
            link[i].style.backgroundColor = "";
            link[i].style.color = "";
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.