jQuery – class manipulation

So, now that we’ve fully exhausted the topic of how to select elements using jQuery, what can we do with it?

Well, one thing we can do is use the two built-in methods, addClass and removeClass, to change the look of your site on the fly.

Given the following HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
<link rel="stylesheet"
  type="text/css"
  href="App_Themes/Main/StyleSheet.css" />
<script src="js/jquery-1.2.6.min.js"
  type="text/javascript"></script>
<script src="default.js"
  type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="main" class="red">
    Here is some text
    </div>
    </form>
</body>
</html>

and the following CSS:

.red
{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    color: #FF0000;
}

.blue
{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    color: #0000FF;
}

If we run the HTML we will see red text for “Here is some text”

Now, if we place the following code in our default.js file:

$(function() {
$("#main").addClass("blue")
    .removeClass("red");
});

the text will be blue instead of red.

We’ve used the addClass() method to add the blue class to the element with the ID of “main” and we’ve used the removeClass method to remove the red class.

The other thing we’ve taken advantage of in this demo is the fact that all of the methods in jQuery return the original selector unless part of their functionality is to return a different set of elements.  This allows us to chain the methods together in much the same way that we could chain input and output streaming operators in C++ (for those of you who know C++).

 


Other post in jQuery

Other Related Items:

Every Extend ExtraEvery Extend ExtraEvery Extended Extra is a unique arcade-style puzzle experience! When your ship enters a colorful vortex, you're sucked into the action as you take on... Read More >
DSi/DS Lite Screen Shield and Cleaning ClothDSi/DS Lite Screen Shield and Cleaning ClothSCREEN SHIELD AND CLEANINGCLOTH
DonkeyDonkeyBrazil's CSS release their follow-up to 2006's "Cansei de Ser Sexy" ("I got tired of being sexy"). They've toured worldwide a number of times with the... Read More >

If you're new here, you may want to subscribe to the mailing list to get notifications of new post and a virtual tour of past topics. Thanks for visiting!

Related Post

One Response to “jQuery – class manipulation”

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor