Can I rewrite Javascript without using 'this'?


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

Here is my code

jQuery(' li').each(function() {

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'?


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.

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(' li').removeClass('current-menu-item').removeClass('current_page_item');

Or (it's the same) :

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

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


Do you mean :

jQuery(' 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(' li').click(function(){
  // Remove class on each item
  jQuery(' li').removeClass('current-menu-item current_page_item');

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