Chain methods jQuery

 
<!DOCTYPE html> 
<html>
    <head>
        <style type="text/css">
            .class1 { 
                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/Book/JavaScriptDemo/jQuery/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">blah blah blah</p>
        </div> 
    </body> 
</html>
  

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

 
<!DOCTYPE html> 
<html>
    <head>
        <style type="text/css">
            .class1 { 
                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/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script> 
        <script type="text/javascript">
            $(function(){
                $("#myDiv") 
                .addClass("class1") 
                .find("p#blah") 
                .removeClass("class1") 
                .addClass("class1");
            });
        </script> 
    </head> 
    <body>
        <div id="myDiv"> 
            <p id="lorem">Lorem Ipsum</p> 
            <p id="blah">blah blah blah</p>
        </div> 
    </body> 
</html>
  
Home 
  JavaScript Book 
    jQuery  

Introduction:
  1. The jQuery Basics
  2. Pattern of using jQuery
  3. Chain methods jQuery
  4. Using jQuery with Other Javascript Libraries