javascripthtmljquerybootstrap-4megamenu

Select an element if the href value is a specific word


Hi and thanks in advance for your help!

I have previously used JS to add an active class to an element if the corresponding URL shows.

I am trying to take what I have done in the past and edit it.

I am trying to add an active class to an element if the href attribute equals '#tab1' for example. Rather than if the URL matches.

Please see the existing JS below that I am trying to work from, I have tried a few things including a getelementbyID rather than selecting the href but I'm lost.

$(document).ready(function () {
  const $links = $('.hs-mega-menu ul li a');
  $.each($links, function (index, link) {
    if (link.href == (document.URL)) {
      $(this).addClass('active');
    }
  });
}); 

An example of one of the nav-links I am trying to select and apply the active class too are below:

<li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>

Solution

  • There are a few ways to do this, you can use a function like you have or you can filter or just use a selector for the attribute. Here are examples of the latter two.

    $(function() {
      let testurl = "#tab1";
      const $links = $('.hs-mega-menu ul li a');
      $links.filter(function(index, link) {
        return $(this).attr('href') == testurl;
      }).addClass("active");
    
      $links.filter("[href='" + testurl + "']").addClass("active-test")
    });
    .active {
      color: green;
    }
    
    .active-test {
      background-color: #ffddff;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="hs-mega-menu">
      <ul>
        <li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
        <li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab1" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
        <li class="nav-item"> <a class="nav-link g-py-10--md g-px-15--md" href="#tab2" role="tab" data-toggle="tab">Printed Stationery<i class="g-ml-10 fa-solid fa-caret-down d-sm-none"></i></a> </li>
      </ul>
    </div>