jQuery practice

Pattern of using jQuery

The typical usage of jQuery is

  1. selecting a DOM element(s)
  2. performing some operation or manipulation on the selected element(s).

The basic call to jQuery is

$(selector);

where selector is an expression for matching HTML elements. The selector format is the same used with CSS. For example, # matches elements by their id attribute and . matches by CSS classes. To get a div with the ID myDiv use the following:

$("div#myDiv");

$() returns a wrapper object. A wrapper object is array-like. When you call a jQuery method, it applies the method to all of the selected elements. There's no need to iterate over the collection with a loop.

The following code shows how to chain jQuery methods together.


<!DOCTYPE html> 
<html>
<head>
<style type="text/css">
    .class1 { <!-- www. ja va  2s .  c  om-->
        color: "white"; 
        background-color: "black"; 
        width:200px; 
        height:100px; 
    }
    .class2 { 
        color: "yellow"; 
        background-color: "red"; 
        width:100px; 
        height:200px; 
    }
</style> 
<script type="text/javascript" 
        src="http://java2s.com/style/jquery-1.8.0.min.js"></script> 
<script type="text/javascript">
    $(function(){ 
        $("#myDiv").addClass("class1"); 
        $("p#blah").removeClass("class1"); 
        $("p#blah").addClass("class1");
    });
</script> 
</head> 
<body>
    <div id="myDiv"> 
        <p id="lorem">Lorem Ipsum</p> 
        <p id="blah">java2s.com java 2s.com and j ava2s.com</p>
    </div> 
</body> 
</html>

Click to view the demo

Here's the rewritten example using chaining instead of separate instances:


<script type="text/javascript">
    $(function(){//  w  w w .  ja v  a 2  s . c o m
        $("#myDiv") 
        .addClass("class1") 
        .find("p#blah") 
        .removeClass("class1") 
        .addClass("class1");
    });
</script> 

The code above generates the following result.

jQuery practice
Home »
  Javascript Tutorial »
    jQuery »
      Introduction
Javascript Tutorial Introduction
jQuery Basics
jQuery practice