Kinglybird
Kinglybird

Reputation: 319

How to convert chained jQuery methods to vanilla js?

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

Answers (2)

vsync
vsync

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

In Chrome 105+ you can use the :has pseudo selector:

document.querySelector(`.menu li:has(a[href="${url}"])`).classList.add('active')

Upvotes: 3

GrafiCode
GrafiCode

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

Related Questions