Home >Web Front-end >JS Tutorial >Analysis on the use of .add() in jquery_jquery

Analysis on the use of .add() in jquery_jquery

WBOY
WBOYOriginal
2016-05-16 17:35:16981browse

add() Adds an element to the collection 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

Copy code The code is as follows:

< ;!DOCTYPE html>




<script><br> $(document).ready(function(){<br> $("div").css("border", "2px solid red").add("p").css("background", "yellow" );<br>});<br></script>







< /div>

Added this… (notice no border)





The result is as shown below:


Explanation: add("p") here means the sum, that is, the css of $("div") and the css of p. Note here that the div has a border. And p does not.

Example 2

Copy code The code is as follows:

< ;body>

Hello

Hello Again


Copy code The code is as follows:

$("p").add("span").css("background", "yellow" );

The result is as shown below:



p and span css, equivalent to

$("p,span").css("background","yellow");

Example 3:

Copy code The code is as follows:


Hello




Copy code The code is as follows:

$("p").clone().add("Again").appendTo(document.body);

The results are as follows:

Clone() means to copy; copy a 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:

Copy the code The code is as follows:

<script><br>$ (document).ready(function(){<br> $("p").add("<span>Again</span>").appendTo(document.body);<br> alert($(" body").html());<br>});<br></script>


Hello





The result is as shown below:



Example 4:

Copy code The code is as follows:


Hello

Hello Again


Copy code The code is as follows:

$("p").add(document.getElementById ("a")).css("background", "yellow");

The results are as follows:

This shows that the parameters in add() can be not only selectors, but also DOM elements.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn