jquery
  1. jquery-wrap

jQuery wrap()

The jQuery wrap() method is a versatile way to add structure and layout to your HTML elements. It allows you to wrap an HTML structure around selected elements, effectively changing their position and layout on the page.

Syntax

The syntax for the wrap() method is as follows:

$(selector).wrap(wrapper);

Where selector is the element(s) you want to wrap and wrapper is the HTML structure you want to wrap around it.

Use

The wrap() method is useful for adding structure and layout to your HTML elements. It can be used to create custom layouts and styles for elements on your page. Additionally, it can be used to reposition elements on the page, making them easier to interact with or visually appealing.

Example

Here is an example of using the wrap() method:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Wrap() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .wrapper {
            border: 1px solid black;
            padding: 10px;
       margin:8px;
        }
    </style>
</head>
<body>
    <div class="outer">
        <p>This is some text.</p>
    </div>
    <script>
        $(document).ready(function() {
            $('p').wrap('<div class="wrapper"></div>');
        });
    </script>
</body>
</html>
Try Playground

In this example, we use the wrap() method to wrap a div element with a class of wrapper around the p element. The wrapper class is defined in the style section to add a border and padding to the wrapped element.

Summary

The wrap() method is a versatile way to add structure and layout to HTML elements using jQuery. It allows you to wrap an HTML structure around selected elements, effectively changing their position and layout on the page. Use it to create custom layouts and styles for elements, as well as repositioning elements on the page to make them easier to interact with or visually appealing.

Published on: