jQuery wrap() Method

jQuery | wrap() Method: Learn about the jQuery wrap() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 17, 2022

wrap() Method

By the word 'wrap' we can presume that it will cover the selected element with some specified content. Wrapping something means covering it to protect it. Therefore, the jQuery wrap() method also does the same job. The wrap() method helps to wrap a particular element with some selected content all around. It will execute on every matched element on the page.

wrap() Method Syntax

$('selector').wrap('Wrapping-content', function());

The wrap() method accepts two parameters – wrappingContent & function. The selected content or element is passed in order to wrap the selector with that. The wrappingContent accepts HTML elements, DOM elements, jQuery objects. The function is an optional parameter which can be passed to execute some set of instructions. The wrap() method returns the changed/wrapped element. Following example shows the implementation of this method more precisely. When the button provided is clicked, the selected element gets wrapped into some predefined properties.

jQuery wrap() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
    <style>
      span{
      color: teal;
      font-size: larger;
      font-weight: bolder;
      font-family: 'Courier New', Courier, monospace;
      }
    </style>
  </head>
  <body>
    <h2>jQuery - Wrap</h2>
    <p>Click the following button to wrap the element with some content.</p>
    <button>Wrap</button>
    <hr>
    <h4>Hey Everybody !!!</h4>
  </body>
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $('h4').wrap('<span></span>');
        })
    });
  </script>
</html>

Output:

Example 1: jQuery wrap() Method



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.