简体   繁体   中英

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!

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM