[SOLVED] Dynamically adding highlight background on active navigation link in Webpage. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[SOLVED] Dynamically adding highlight background on active navigation link in Webpage.

I want to add a highlight to a corresponding link in a navigation menu when the related page is open. And I tried the following code and it is working perfectly, but It seems lengthy. How can I do this in a easier, shorter and smarter way Code: let navLinks = document.querySelectorAll(".header .menu ul li"); /*navLinks structure: Home => /index.html or site name only About => /about.html Contact => /contact.html Signup => /join.html ....................*/ let linkPath = window.location.href; if(/localhost:8158$/.test(linkPath) || /localhost:8158\/index/.test(linkPath)) { navLinks[0].classList.add("active"); } if(/localhost:8158\/about/.test(linkPath)) { navLinks[1].classList.add("active"); } if(/localhost:8158\/contact/.test(linkPath)) { navLinks[2].classList.add("active"); }

31st Oct 2020, 7:01 AM
Bibek Oli
Bibek Oli - avatar
5 Answers
+ 2
right... edit el.parentNode.classList.add('active')
31st Oct 2020, 9:31 AM
KrOW
KrOW - avatar
+ 2
if you insert an anchor tag inside li elements you can do something like let ps= document.querySelectorAll('.header .menu ul li a') ps= Array.from(ps) ps.forEach((el)=>{ if(el.href==window.location.href){ el.classList.add('active') } })
31st Oct 2020, 7:31 AM
KrOW
KrOW - avatar
+ 1
KrOW yes, there is anchor tag inside li tag, but selecting the <a> tag highlight only the text, so I am selecting the parent of <a> i.e. li to get expected result.
31st Oct 2020, 7:46 AM
Bibek Oli
Bibek Oli - avatar
+ 1
KrOW thank you.🙂
31st Oct 2020, 11:22 AM
Bibek Oli
Bibek Oli - avatar
+ 1
👍🏻
31st Oct 2020, 12:16 PM
KrOW
KrOW - avatar