This article introduces the analysis of the use of .add() in jquery. Friends who need it can refer to
add() to add elements to the set of matching elements. This is the statement in the jquery reference manual. However, the example link provided is wrong, so there is no example description of add(). Here are a few examples to better understand the usage of add().
Example 1
The code is as follows:
<!DOCTYPE html> <html> <head> <style> p { 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(){ $("p").css("border", "2px solid red").add("p").css("background", "yellow"); }); </script> </head> <body> <p></p> <p></p> <p></p> <p></p> <p></p> <p></p> <p>Added this… (notice no border)</p> </body> </html>
The result is as shown below:
Explanation: add("p") here means sum, that is, the css of $("p") and the css of p. Note here that p has a border. And p does not.
Example 2
The code is as follows:
<body> <p>Hello</p><span>Hello Again</span> </body>
The code is as follows:
$("p").add("span").css("background", "yellow");
The result is as shown in the figure below Display:
## The css of p and span is equivalent to
$("p,span").css("background","yellow");
<body> <p>Hello</p> </body>
$("p").clone().add("<span>Again</span>").appendTo(document.body);
The result is as follows:
clone() means to copy; copy one p and insert Again into the body of the document. Insert a sentence here: If clone() is not used, the original p will no longer exist. Look at the following example:<script> $(document).ready(function(){ $("p").add("<span>Again</span>").appendTo(document.body); alert($("body").html()); }); </script> <body> <p>Hello</p> </body>