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

Related Post

One Response to “jQuery – class manipulation”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear