My code:
JavaScript
x
7
1
const address = location.pathname;
2
const links = document.querySelectorAll('.sidebarMain a');
3
4
links.forEach(function(el) {
5
if(new RegExp(`^${el.getAttribute('href')}(.*)$`, 'i').test(address))
6
el.classList.add('active')});
7
But it doesn’t work, where did I go wrong?
Advertisement
Answer
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
1
10
10
1
let links = document.querySelectorAll(".sidebarMain a");
2
let cur = window.location.href;
3
4
console.log(cur)
5
6
links.forEach(function(link){
7
if(link.getAttribute("href") == cur){
8
link.classList.add("active");
9
}
10
});
JavaScript
1
1
1
.active{font-weight:bold;color:red;}
JavaScript
1
4
1
<div class="sidebarMain">
2
<a href="https://stacksnippets.net/js">Active</a>
3
<a href="aaa">test3</a>
4
</div>