Home > other >  How to convert chained jQuery methods to vanilla js?
How to convert chained jQuery methods to vanilla js?

Time:09-01

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!

CodePudding user response:

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')

CodePudding user response:

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 >
  <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>

  • Related