jQuery DOM manipulation wrap()
If you want to wrap an element with other elements, that is, add a parent element to it. For such processing, JQuery provides a wrap method
.wrap(wrappingElement): matched in the collection An HTML structure is wrapped around each element
For example, let’s write an example below
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <p>php 中文网</p> <script> $("p").wrap("<div></div>"); </script> </body> </html>
Friends, look at the above code, so that we add a parent node to the p tag. Friends, put Copy the code to run locally and press F12 to view
wrap( function ): a callback function that returns the HTML content or jQuery object used to wrap the matching element
The effect after use is the same as passing parameters directly, except that the code can be written inside the function body, the writing method is different
Let’s take a look at the example below:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <p>php 中文网</p> <script> $('p').wrap(function(){ return '<div>'; }) </script> </body> </html>
My friends, you can Run the second one. In fact, the effect is the same as the first one, but the writing method is different.
Note: The wrap() function can accept any string or object and can be passed to the $() factory function. to specify a DOM structure. This structure can be nested several levels deep, but should only contain a core element. Each matching element will be wrapped by this structure. This method returns the original set of elements so that the chaining method can be used later.