Categories

Adding / Removing Classes and Attributes Using jQuery

Adding and Removing attributes on elements is simple. With jQuery you can easily add or remove classes, add or remove attributes, as well as many more effects. First, as with any jQuery script, you will need to write the document ready function to start using your jQuery functions.

$(function() {
            // code goes here
});

Lets say we had some html elements as follows:

<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>

If we wanted to add a class to every other p tag we could simply use the selectors while also applying some additional methods. For instance:

$(‘p:even’).addClass(‘evenps’);  // adds the class evenps to every other even p element.
$(‘p:odd).addClass(‘oddps’);  // adds the class oddps to every other odd p element.

The same would apply if we wanted to remove a class from the p tags.

$(‘p:even’).removeClass(‘evenps’);  // removes the class evenps to every other even p element.
$(‘p:odd).removeClass(‘oddps’);  // removes the class oddps to every other odd p element.

Lets say we wanted to add specific attributes without using css classes. We could use the attr() method.

$(‘p:even’).attr(‘color’, ‘white’);  // this would set the color for the even p’s to white.

You could set any style using the attr method. Not only can you set attributes using this method. You can also get the value of existing attributes.

$(‘p:even’).attr(‘color’);  // this would return the value of the attribute color.

Contact Details

Frank Perez Contact Information

Frank Perez
Phone: 1-954-560-8165
Email: frank@frankperez.net

Messengers:
MSN: frank@frankperez.net
AIM: frankperez87
G-Talk: frankperez87@gmail.com
Skype: frankperez87

Contact Frank Perez