search
HomeWeb Front-endJS TutorialDetailed explanation of jQuery.wrap() function

Detailed explanation of jQuery.wrap() function

Jun 24, 2017 pm 01:33 PM
functionDetailed explanation

The wrap() function is used to wrap the specified HTML structure outside each matching element.

The opposite of this function is the unwrap() function, which is used for the parent element of the currently matched element (only the parent element is removed, and all its internal nodes are retained).

This function belongs to the jQuery object (instance).

Syntax

jQueryObject.wrap( wrapper )

Parameters

Parameter Description

wrapper ## The #String/Element/jQuery/Function type is used to wrap nodes that match elements.

If the parameter wrapper is a

string, it will be regarded as a jQuery selector or html string, and jQuery will make its own judgment.

jQuery 1.4 New support: parameter wrapper can be a function. wrap() will traverse and execute the function based on all matching elements, and this in the function will point to the corresponding DOM element.

wrap() also passes a parameter to the function, which is the index of the current element in the matching element.

The return value of the function is the node content used for wrapping (can be an html string, DOM element or jQuery object).

Note: If wrapper matches multiple elements, only the first element will be used as the wrapping element.

Note: If the wrapper is a multi-layer nested element (such as

), wrap() will check each layer from the outside in. The first node of the nest. If the node has no child nodes or the first child node is not an Element node (such as text node, comment node, etc.), stop searching inward and directly append (append()) the current matching element at the end position inside the current node.

Return value

The return value of the wrap() function is of jQuery type, returning the current jQuery object itself (to facilitate chain-style programming).

Note: Even if the wrapper element is an element in the current page, the element will not disappear from its original position. Because wrap() uses a copy (clone) of the element to act as a wrapper.

Example & Description

The wrap() function is used to insert content before each matching element:

<p>段落文本1<span></span></p>
<p>段落文本2<span></span></p>
<script type="text/javascript">
$("p").wrap( &#39;<div></div>&#39; ); 
</script>
<!--以下是jQuery代码执行后的html内容-->
<div><p>段落文本1<span></span></p></div>
<div><p>段落文本2<span></span></p></div>

Take the following HTML code as an example:

<p id="n1">
    <span id="n2">span#n2</span>    
</p>
<p id="n3">
    <input id="n4" type="text" />
</p>
<span id="n5">多层嵌套1</span>
<span id="n6">多层嵌套2</span>

The following jQuery sample code is used to demonstrate the specific usage of the wrap() function:

// 在n2元素外包裹strong元素:<strong>{#n2}</strong>
$("#n2").wrap(&#39;<strong/>&#39;);// 在n4元素外包裹form元素:<form name="myForm">{#n4}</form>
$("#n4").wrap(&#39;<form name="myForm"></form>&#39;);
// 在每个p元素外包裹div元素:<div data_id="index">{p}</div>
$("p").wrap( function(index){
    return &#39;<div data_id="&#39; + index + &#39;"></div>&#39;;   
} );
// 在n5元素外包裹嵌套的div元素:<div><p><em><b>{#n5}</b></em></p></div>
$("#n5").wrap( &#39;<div><p><em><b></b></em></p></div>&#39; );
// 在n6元素外包裹嵌套的div元素:<div><p> <em><b></b></em>${#n5}</p></div>
// wrap()会从外层div依次往内部查找,以确定n5元素的所在位置
// wrap()将从外往内检查每层嵌套的第一个元素,如果该元素没有子元素或者第一个子元素不是Element节点,就停止向内查找
// 由于参数的&#39;<p>&#39;后面有空格(文本节点),也就是说p元素的第一个子元素不是Element类型,因此直接将n6插入到p元素内部的末尾位置
$("#n6").wrap( &#39;<div><p> <em><b></b></em></p></div>&#39; );
wrap()会将包裹元素的开始标记和结束标记分别置于匹配元素的两侧,不会额外添加任何空白字符,上述代码执行后的完整html代码如下(格式未作任何调整):
<div data_id="0"><p id="n1">
    <strong><span id="n2">span#n2</span></strong>    
</p></div>
<div data_id="1"><p id="n3">
    <form name="myForm"><input id="n4" type="text"></form>
</p></div>
<div><p><em><b><span id="n5">多层嵌套1</span></b></em></p></div>
<div><p> <em><b></b></em><span id="n6">多层嵌套2</span></p></div>

The above is the detailed content of Detailed explanation of jQuery.wrap() function. For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools