There is a code by which I select active links:

onload = function () { for (var lnk = document.links, j = 0; j < lnk.length; j++) if (lnk [j].href == document.URL) lnk [j] .style.cssText = 'background-color: #418CD0;'; } 

But it does not work as I would like. The fact is that I bring the news to the main page (In this case, the link to the Main page is highlighted in navigation), but when I switch to another page URL/?page=n or when I go to the news news/?id=n , then the Highlight the page disappears, but I would like it to be highlighted, as the news and navigation through the pages are on the Main page.

Please help. Thank you so much in advance!

  • Instead of document.URL try using document.URL.split(/[\?#]/)[0] . - Visman
  • See what your lnk [j] .href is for such a link. - nick_n_a
  • likely var lnk = document.getElementsByTagName('a') instead of document.links - Jean-Claude

2 answers 2

 onload = function () { var lnk = document.getElementsByTagName('a'); for (var i= 0; i < lnk.length; i++) if (lnk[i].href == document.URL) { lnk[i].style.cssText = 'background-color: #418CD0;'; } } 
     onload = function () { var lnk = document.getElementsByTagName('a'); for (var i= 0; i < lnk.length; i++) if (lnk[i].href == document.URL.split(/[\?#]/)[0]) { lnk[i].style.cssText = 'background-color: #418CD0;'; } } 

    thank