Can I rewrite Javascript without using 'this'?

advertisements

I'm very new to JS and I'm having trouble getting this to work.

Here is my code

jQuery('ul.menu li').each(function() {
jQuery(this).removeClass('current-menu-item');
jQuery(this).removeClass('current_page_item');
});
jQuery(this).parents('li').addClass('current_page_item');
jQuery(this).parents('li').addClass('current-menu-item');

Now what this should be doing is remove the highlight from one link on a navigation menu, and highlighting the one thats been clicked (I have an AJAX implementation).

For some reason it isn't doing anything. I have a feeling it is due to 'this' is there another way of structuring this code so I can work out if the code is wrong, which I don't believe it to be, or because of 'this'?

EDIT:

Apologies, it seems I haven't given enough information. I'm using the Twenty Fourteen wordpress theme but I'm serving the pages with AJAX.

http://twentyfourteendemo.wordpress.com/

I have the code being applied globally (I have other code in the same place to toggle the navigation once clicked (on mobile) and that works fine)

I have the menu at the top (without any dropdowns, just links). I can't give a link as it's not external currently. Should my code be working to change this?

As a few people have commented "What is 'this'" I feel I've completely missed something.


You don't need loop each item to do a remove class one by one, this is more easy :

jQuery('ul.menu li').removeClass('current-menu-item').removeClass('current_page_item');

Or (it's the same) :

jQuery('ul.menu li').removeClass('current-menu-item current_page_item');

But I don't understand what is this 'this' :

jQuery(this).parents('li').addClass('current_page_item');
jQuery(this).parents('li').addClass('current-menu-item');

Do you mean :

jQuery('ul.menu li').addClass('current_page_item current-menu-item');

Or if you are on an event listener (like click, as @Daniel Sanchez feel on comment) you just need to do :

jQuery('ul.menu li').click(function(){
  // Remove class on each item
  jQuery('ul.menu li').removeClass('current-menu-item current_page_item');

  // Add class for this one
  jQuery(this).addClass('current_page_item current-menu-item');
})