Add () adds the element to the set of matching elements. This is the expression in the jquery reference manual. However, the link to the provided example is incorrect, so there is no description of the add () instance. Here are a few examples to better understand the use of add.
Example 1
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Style>
Div {width: 60px; height: 60px; margin: 10px; float: left ;}
P {clear: left; font-weight: bold; font-size: 16px;
Color: blue; margin: 0 10px; padding: 2px ;}
</Style>
<Script language = "JavaScript" type = "text/JavaScript" src = "http://www.w3school.com.cn/jquery/jquery.js"> </script>
<Script>
$ (Document). ready (function (){
$ ("Div" ).css ("border", "2px solid red"). add ("p" ).css ("background", "yellow ");
});
</Script>
</Head>
<Body>
<Div> </div>
<Div> </div>
<Div> </div>
<Div> </div>
<Div> </div>
<Div> </div>
<P> Added this... (Notice no border) </p>
</Body>
</Html>
The result is shown in:
Explanation: The add ("p") Here is equivalent to the sum, that is, the css of $ ("div") and the css of p. Note that the div has a border. P does not.
Example 2
Copy codeThe Code is as follows:
<Body>
<P> Hello </p> <span> Hello Again </span>
</Body>
Copy codeThe Code is as follows:
$ ("P"). add ("span" ).css ("background", "yellow ");
The result is shown in:
The css of p and span is equivalent
$("p,span").css("background","yellow");
Example 3:
Copy codeThe Code is as follows:
<Body>
<P> Hello </p>
</Body>
Copy codeThe Code is as follows:
$ ("P"). clone (). add ("<span> Again </span>"). appendTo (document. body );
The result is as follows:
Clone () indicates copying. Copy A p file and insert <span> Again </span> to the body of the document.
If clone () is not used, the original p does not exist. Take the following example:
Copy codeThe Code is as follows:
<Script>
$ (Document). ready (function (){
$ ("P"). add ("<span> Again </span>"). appendTo (document. body );
Alert ($ ("body" example .html ());
});
</Script>
</Head>
<Body>
<P> Hello </p>
</Body>
</Html>
The result is shown in:
Example 4:
Copy codeThe Code is as follows:
<Body>
<P> Hello </p> <span id = "a"> Hello Again </span>
</Body>
Copy codeThe Code is as follows:
$ ("P"). add (document. getElementById ("a" example .css ("background", "yellow ");
The result is as follows:
This indicates that the parameter in add () can be either a selector or a DOM element.