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
Ads by Lake Quincy Media

Other Related Items:

Mastering PHP 5.0 (5 Disc Value Pack) Includes: FrontPage 2003 + Dreamweaver MX 2004Mastering PHP 5.0 (5 Disc Value Pack) Includes: FrontPage 2003 + Dreamweaver MX 20045 CD Value Pack: Mastering PHP 5.0 (disc 1) Mastering PHP 5: Professional learning from the source (disc 2) Mastering Javascript 2004 (disc 3) Mastering Dreamweaver MX 2004 (disc 4) Mastering Frontpage 2003 (disc 5)
Soffe Juniors' Printed Soffe ShortSoffe Juniors' Printed Soffe ShortRelax after a big win in the MJ Soffe® Novelty Print women's short. It features a comfortable elastic waistband for an optimal fit and v-notch hems for an enhanced range of motion.

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Related Post

One Response to “jQuery – class manipulation”

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor