This jQuery beginning tutorial shows how to declare variable. It also shows how to write simple jQuery codes to get the dimension of an image on a web page. Finally, this jQuery beginner tutorial shows how to hide elements on web page.

Watch jQuery Element Class Beginner video tutorial on YouTube:

This jQuery tutorial shows how to add class, remove class and swap class (toggle class) of selected element to provide interesting effect of a Horizontal Navigation Menu.

Goal of jQuery Element Class Tutorial

This jQuery example shows how to add class, remove class and toggle class when click on a Menu Item of Horizontal Navigation Menu. This can provide interesting hightlight effect to clicked Menu Items.

HTML Codes of Horizontal Navigation Menu:

Following is the HTML codes of the Horizontal Navigation Menu. Note that there is no any class attached to the menu items. The class will be added “dynamically” to the menu items when mouse pointer click on them.

#mainNavMenu .changeColor {
background-color: #F00;
}

#mainNavMenu .emphasisColor {
background-color: #F90;
}

And this is the class added to the stylesheet:

<div id="mainNavMenu">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">New Product</a></li>
<li><a href="#">My Account</a></li>
<li><a href="#">Shopping Cart</a></li>
<li><a href="#" style="background-image:none;">Check Out</a></li>
</ul>
</div>

The following jQuery element class examples are used in the video tutorial. The codes are explained very details in the video tutorial.

jQuery Remove Class and Add Class Example

In this example, the clicked menu item will be changed to red color. Here’s how the jQuery codes works when a Menu Item is clicked:

  • Remove the class that add before. This step is required otherwise the background color of all clicked menu items will be red color.
  • Add the class “changeColor” to the clicked menu item. Therefore the background color of the clicked menu item will be changed to red color.
// Declare a variable for the selected element
var targetElement = $("#mainNavMenu li");

targetElement.click(function() {
// Remove the class if added before
targetElement.removeClass();

// Add class to clicked menu item
$(this).addClass("changeColor");
})

jQuery Remove Class, Add Class and Toggle Class Example

This jQuery element class example is almost the same as the previous one, except that when the current clicked menu item is clicked again, it will changed from red color to brown color. This can be achieved by swapping or toggle the class.

Here’s the codes:

targetElement.click(function() {
if ( $(this).is(".changeColor") ) {
// Change or swap the class if a class already exist
$(this).toggleClass("changeColor emphasisColor")

} else {
// Remove the class if added before
targetElement.removeClass();

// Add class to clicked menu item
$(this).addClass("changeColor");
}
});

This is the end of jQuery Element Class Tutorial.