Log In | Register | April 16, 2024

Share
 

jQuery Programming - August 31, 2010

Adding / Removing Classes and Attributes Using jQuery

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.

Post By: | FavoriteLoadingAdd to favorites

3 Comments

media.nguoixaxu.com
Friday, July 4, 2014

Daѕ ist die ƅeste Netzseite, die icɦ je gesehen habe.

드림카지노 | www.gkv55.com | DREAMCASINO | 바카라사이트
Thursday, April 2, 2020

Dreamcasino provides quality online casino services with strong funding, friendly service, and operational know-how of Dreamcasino. It offers a variety of events and benefits and is doing its best to grow into the best brand of online casino.

sex freies spiel 3d
Monday, August 3, 2020

Writing document for JQuery script for having any wanted function.There are many possible function if the proper document have ready. Thanks for letting us know this document for adding/removing classes with JQuery.

Leave a Comment



Need Help? Ask a Question

Ask anything you want from how to questions to debug. We're here to help.

You Must Be Logged In To Post A Question.

Log In or Register