Javascript menu enlazado a páginas html

I have been trying to change background color of a hyperlink (a tag) or a li tag when a new page load. I understandd this can be made with javasccript and css. But the menu ul li only chhhanges its backgrround color when href of <a> is equal too #. When i assign it the url of a page (like contacto.html) the background does not change its color. I have this code in javascript:

'use strict'
window.onload = func() {
init();
var l = document.querySelectorAll('li  a');
l.forEach((cadaL, i)=>{
//Asignar un click a cada enlace (L)
   l[i].addEventListener('click', ()=>{
        //Recorrer todos los l
         l.forEach((cadaL, i)=>{
         //Quitando la clase activo de cada l
              l[i].classList.remove('activo');
         });
    //En el enlace(l) que hacemos click le añadimos clase activo
if (document.readyState == "complete") {
         l[i].classList.add('activo');
}
    });
});
}

Can you help me please. Thanks.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

I don’t if this would make any difference, but the selector to select a inside li is with a single space

use the function parameter, cadaL, what’s the point of using a forEach if you are going to reference global variables anyway?

I have changed your code to add proper formatting:

'use strict'
window.onload = func() {
  init();
  var l = document.querySelectorAll('li  a');
  l.forEach((cadaL, i) => {
    //Asignar un click a cada enlace (L)
    l[i].addEventListener('click', () => {
      //Recorrer todos los l
      l.forEach((cadaL, i) => {
        //Quitando la clase activo de cada l
        l[i].classList.remove('activo');
      });
      //En el enlace(l) que hacemos click le añadimos clase activo
      if (document.readyState == "complete") {
        l[i].classList.add('activo');
      }
    });
  });
}

if you give it a different href, it reloads the page

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.