Add active class to link with current page

Solution:1

According to WordPress Code reference page: wp_nav_menu()#menu-item-css-classes, the class below is added to menu items that correspond to the currently rendered page.

  • .current-menu-item

So, basically what you can do is to just add the corresponding css for the class names which are automatically generated by wordpress:

.current-menu-item {
    color: red; // change the color of the current active page to #red;
}
.current-menu-parent {
    // current active menu's parent styles
}

You don’t need to use jQuery.

Solution:2

<script>
  jQuery(function($) {
      var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
        $(".navbar-nav > li > a").each(function(){
        if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
        $(this).addClass("active");
        // $(this).parent("li").addClass("active");
      })
  });
</script>

Add active class to menu

Based on navigation structure you can write the jquery, here .active class add to .navbar-nav > li > a, so depends on menu write code.

Solution:3

<script>
function func(){
document.getElementById(‘div’).classList.add(‘active’);
}
</script>

<button onclick=’func()’>Click</button>
<div id=”div”>
This element gets ‘active’ class.
</div>


Solution:4

jQuery(function($) {
var path = window.location.href; // because the ‘href’ property of the DOM element is the absolute path
$(‘ul a’).each(function() {
if (this.href === path) {
$(this).addClass(‘active’);
}
});
});