JQuery Functions [wrap-wrapInner-wrapAll-unwrap]

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

In the previous post JQuery Functions [html-append-prepend] I talked about some JQuery functions which are html, append and prepend and they are called DOM Insertion, Inside functions.

In this post I will talk about DOM Insertion, Around functions which are :

.wrap()

let’s consider that we have this html code






<div class="container">
  <div class="hello">Hello</div>
  <div class="world">World</div>
</div>

and we wanted to put the div with the class=’hello’ in a new div with a class=’new’



















// the html code
<div class="container">
  <div class="hello">Hello</div>
  <div class="world">World</div>
</div>
 
// the jquery code
$('.hello').wrap('<div class="new">');
 
// the result
<div class="container">
  <div class="new">
  <div class="hello">Hello</div>
  </div>
  <div class="world">World</div>
</div>
</div>

.wrapInner()

let’s consider that we have this html code






<div class="container">
  <div class="hello">Hello</div>
  <div class="world">World</div>
</div>

and we wanted to put a new div with the class=’new’ in the div with a class=’hello’




















// the html code
<div class="container">
  <div class="hello">Hello</div>
  <div class="world">World</div>
</div>
 
// the jquery code
$('.hello').wrapInner('<div class="new">');
 
// the result
<div class="container">
   
  <div class="hello">
     <div class="new">Hello</div>
  </div>
  <div class="world">World</div>
</div>
</div>

.wrapAll()

the difference between wrap and wrapAll is that when we have the same class repeated the wrap function will cover each item alone, on the other side wrapAll covers all items as unity.



















// the html code
<div class="container">
  <div class="hello">Hello</div>
  <div class="hello">World</div>
</div>
 
// the jquery code
$('.hello').wrapAll('<div class="new">');
 
// the result
<div class="container">
  <div class="new">
    <div class="hello">Hello</div>
    <div class="hello">World</div>
  </div>
</div>
</div>

.unwrap()

The .unwrap() function removes the element’s parent. This is effectively the inverse of the .wrap() function.















// the html code
<div class="container">
  <div class="hello">Hello</div>
  <div class="world">World</div>
</div>
 
// the jquery code
$('.hello').unwrap('<div class="container">');
 
// the result
<div class="hello">Hello</div>
<div class="world">World</div>
</div>

Leave a Comment

Your email address will not be published. Required fields are marked *