[英]How to add class for ACTIVE URL in sidebar?
My code:我的代码:
const address = location.pathname;
const links = document.querySelectorAll('.sidebarMain a');
links.forEach(function(el) {
if(new RegExp(`^${el.getAttribute('href')}(.*)$`, 'i').test(address))
el.classList.add('active')});
But it doesn't work, where did I go wrong?但它不起作用,我哪里出错了?
The HREF of links will automatically include the current domain when accessing via javascript, so you can just directly compare to window.location.href通过javascript访问时链接的HREF会自动包含当前域,所以你可以直接比较window.location.href
let links = document.querySelectorAll(".sidebarMain a"); let cur = window.location.href; console.log(cur) links.forEach(function(link){ if(link.getAttribute("href") == cur){ link.classList.add("active"); } });
.active{font-weight:bold;color:red;}
<div class="sidebarMain"> <a href="https://stacksnippets.net/js">Active</a> <a href="aaa">test3</a> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.