Cover Image for jQuery wrap() method
88 views

jQuery wrap() method

The jQuery wrap() method is used to wrap an HTML structure around each of the selected elements. It allows you to add a wrapping element, such as a <div>, around one or more elements to group them together or apply a common styling or functionality.

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

$(selector).wrap(wrappingElement);
  • selector: It is a string that specifies the elements to be selected.
  • wrappingElement: It can be an HTML string, a DOM element, or a jQuery object that represents the wrapping element you want to add around the selected elements.

Here’s an example of how you can use the wrap() method:

HTML:

<p>This is some text.</p>
<p>This is another paragraph.</p>

JavaScript:

// Wrap each paragraph with a div element
$('p').wrap('<div class="wrapper"></div>');

After executing the above JavaScript code, the two paragraphs will be wrapped with a div element with the class “wrapper”:

Resulting HTML:

<div class="wrapper">
  <p>This is some text.</p>
</div>
<div class="wrapper">
  <p>This is another paragraph.</p>
</div>

You can also use existing DOM elements or jQuery objects as the wrapping element. For example:

JavaScript:

// Create a new div element and use it to wrap the paragraphs
var wrapperElement = $('<div class="wrapper"></div>');
$('p').wrap(wrapperElement);

The wrap() method can be used to add structure to your HTML and make it easier to apply consistent styling or functionality to groups of elements. It is commonly used to create layout structures, apply CSS styles, or prepare elements for additional interactions.

Keep in mind that the wrap() method only wraps the selected elements with the specified wrapping element without cloning or duplicating the original elements. If you need to clone the selected elements before wrapping, you can use the wrapAll() method instead.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS