skip to Main Content

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!

2

Answers


  1. 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')
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search