why are us the wrap method in JQ?

Asked 28-Jul-2021
Viewed 248 times

1 Answer


1

jQuery wrap() is used to wrap the selected HTML in an another html tag. this wrap() can accept any type of data like tagname, string, or object etc. 

Syntax:
$(selector).wrap(wrap data)
$(selector).wrap(wrap data, function(index))

Example :

<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
    <script type='text/javascript'>
        $(document).ready(function () {
            $('button').click(function () {
                var content = '<div> </div>'
                $('p').wrap(content);
            });
        });
    </script>
    <style>
        body {
            margin: 10px;
            padding: 10px;
        }
        div {
            background-color: cyan;
            color: white;
            text-align: center;
            font-size:20px;
            height:100px;
            line-height:80px;
        }
    </style>
</head>
<body>
    <button>Click me for wrap the data</button>
    <p>click button for wrap the data in div tag with css</p>
</body>
</html>

Output:

why are us the wrap method in JQ?