Home >Web Front-end >Front-end Q&A >How to add parent tag in jquery
In jquery, you can use the wrap() function to add a parent tag to a specified element. Adding method: 1. Use the jquery selector to select the specified element object, the syntax "$(selector)"; 2. Use the wrap() function to add a specified parent element to the obtained element object, the syntax "element object.wrap(html|ele |fn)".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
In jquery, you can use the wrap() function to add a parent tag to a specified element.
jquery wrap()
wrap() method uses the specified HTML element to wrap each selected element, that is, in Adds a parent element outside the selected element.
This kind of wrapping is most useful for inserting additional structured markup into the document without destroying the semantic quality of the original document. The principle of this function is to examine the first element provided (which is dynamically generated from the provided HTML markup code) and find the top-level ancestor element in its code structure - this ancestor element is the wrapping element. This function cannot be used when the element in the HTML markup code contains text. Therefore, if you want to add text, you should add it after the package is completed.
Syntax:
$(selector).wrap(html|ele|fn)
Parameter description:
html Parameter Description: Wrap all paragraphs with a newly created div
$("p").wrap("<div class='wrap'></div>");
$("p").wrap(document.getElementById('content'));
<div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div> $('.inner').wrap(function() { return '<div class="' + $(this).text() + '" />'; });Result:
<div class="container"> <div class="Hello"> <div class="inner">Hello</div> </div> <div class="Goodbye"> <div class="inner">Goodbye</div> </div> </div>
Example of wrap() adding parent tag
to eachElement adds a parent element
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p").wrap("<div></div>"); }); }); </script> <style type="text/css"> div { background-color: yellow; } </style> </head> <body> <p>这是一个段落。</p> <p>这是另一个段落。</p> <button>给每个P元素包裹一个div元素</button> </body> </html>[Recommended learning:
The above is the detailed content of How to add parent tag in jquery. For more information, please follow other related articles on the PHP Chinese website!