Home  >  Article  >  Web Front-end  >  Detailed explanation of jQuery.unwrap() function

Detailed explanation of jQuery.unwrap() function

巴扎黑
巴扎黑Original
2017-06-24 13:49:243567browse

The unwrap() function is used to remove the parent element of each matching element.

unwrap() will remove the parent element of the currently matched element, but will retain all its descendant elements. You can use this function to quickly cancel the parent wrapping element added to the matching element through the wrap() function.

The opposite of this function is the wrap() function, which is used to wrap each matching element with the specified element.

This function belongs to the jQueryobject(instance).

Syntax

jQuery 1.4 NewThis function is added.

jQueryObject.unwrap( )

If the parent element of the currently matched element is the body element, the unwrap() function will not remove the body element.

Return value

unwrap()The return value of the function is of jQuery type and returns the current jQuery object itself (to facilitate chain-style programming).

Example & Description

The unwrap() function is used to remove the parent element of each matching element:

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

The unwrap() function and replaceWith() function have the following, etc. Price code:

$("selector").unwrap( );
// 等价于(父元素为body时除外)
// 用其父元素的所有子节点替换掉父元素
$("selector").parent().replaceWith( function(){
    return $(this).contents();
} );

Take the following HTML code as an example:

<p id="n1">
    <span id="n2">span#n2</span>    
</p>
<p id="n3">
    <label id="n4">label#n4</label>
    <span id="n5">span#n5</span>
</p>
<span id="n6">span#n6</span>

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

// 移除每个span元素的父元素
// n6的父元素为body元素,body元素不会被移除
$("span").unwrap( );

The above code The complete html code after execution is as follows (the format has not been adjusted in any way):

    <span id="n2">span#n2</span>    
    <label id="n4">label#n4</label>
    <span id="n5">span#n5</span>
<span id="n6">span#n5</span>

The above is the detailed content of Detailed explanation of jQuery.unwrap() 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