Try the following: you can wrap your script in $(function(){..}); to ensure that the DOM is ready. You also need to fix your jquery selector, because according to class="nav navbar-nav navbar-right" your selector should be .nav.navbar-nav , not .nav navbar-nav (this means that inside nav there is a child navbar-nav ). See below code
$(function(){ //here instead of ".nav navbar-nav" change it to ".nav.navbar-nav" $('.nav.navbar-nav li a').click(function($) { $('a[href="'+window.location.pathname+window.location.hash+'"]').parent().addClass('active'); }); });
And if you dynamically create these elements, use .on() as shown below -
$(function(){ //here instead of ".nav navbar-nav" change it to ".nav.navbar-nav" $(document).on('click','.nav.navbar-nav li a',function($) { $('a[href="'+window.location.pathname+window.location.hash+'"]').parent().addClass('active'); }); });
source share