Reputation: 319
I know JQuery make our lives much easier, but I'm trying to write some lines in vanilla javascript...so here it goes:
$('.menu a').filter(function() {
return this.href == url;
}).closest('li').addClass('active');
Many thanks!
Upvotes: 0
Views: 96
Reputation: 130195
const url = '#2';
document.querySelectorAll('.menu a').forEach(elem => {
if (elem.getAttribute('href') === url)
elem.closest('li').classList.add('active')
})
// or shorter:
document.querySelector(`.menu a[href="${url}"]`).parentElement.classList.add('active')
.active { background: yellow; }
<ul class='menu'>
<li><a href='#1'>1</a></li>
<li><a href='#2'>2</a></li>
<li><a href='#3'>3</a></li>
</ul>
document.querySelectorAll('.menu a')
- gets all the a
elements inside .menu
document.querySelector(`.menu li:has(a[href="${url}"])`).classList.add('active')
Upvotes: 3
Reputation: 3374
Considering you're matching the href
attribute:
let url = '#l3';
document.querySelector('.menu a[href="' + url + '"]').parentElement.classList.add('active')
li.active a { color: green; }
<ul class="menu">
<li><a href="#l1">link</a></li>
<li><a href="#l2">link</a></li>
<li><a href="#l3">link</a></li>
<li><a href="#l4">link</a></li>
</ul>
Upvotes: 1