• jQuery Video Tutorials

jQuery unwrap() Method



The unwrap() method in jQuery is used to remove the parent element of a selected elements. In other words, it us "unwrapping" a selected element from its parent.

This method doesn't return a value explicitly. It operates directly on the selected element(s), removing their parent element(s) if they match the specified selector.

Syntax

Following is the syntax of unwrap() method in jQuery −

$(selector).unwrap()

Parameters

This method does not accept any parameters.

Example 1

In the following example, we are using the unwrap() method in jQuery to remove the parent element of all paragraph elements −

<html>
<head>
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("p").unwrap();
      });
    });
  </script>
</head>
<body>
  <div style="border: 2px solid green; background-color: yellow; width: 15%;">
    <p>Paragraph element ...</p>
  </div>
  <br>
  <div style="border: 2px solid green; background-color: yellow; width: 15%;">
    <p>Paragraph element 2...</p>  
  </div>
  <br>
  <button>Click</button>
</body>
</html>

The parent elements (div, which wrapped the paragraph elements) will be unwrapped when we click the button.

Example 2

Here, we are unwrapping the first parent element of the paragraph elements −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(document).ready(function(){
        $('button').click(function(){
          $("p").unwrap();
        })
      });
  </script>
</head>
<body>
    <div style="border: 2px solid green; background-color: yellow; width: 15%;">
        <div style="border: 2px solid green; margin-left: 10px; background-color: red; height: 120px; width: 80%;">
            <p>Paragraph 1</p>
            <p>Paragraph 2</p>
        </div>
    </div>
    <button>Click</button>
</body>
</html>

After clicking the button, the first parent element will be unwrapped.

jquery_ref_html.htm
Advertisements