Wrapping all matched elements with another element in jQuery?

Updated on ... 15th February 2023

In this article, we will discuss a jquery technique that is very useful when you are working on a dynamic content website and you want some elements wrapped with another element on the whole page or a specific element using jquery. So, Jquery has a wrap() method that can take any string or object that could be passed to the $() factory function to specify a DOM structure. It may be more level deep, A copy of this structure will be wrapped around each of the existing elements in the set of selected or matched elements. and it will return the original set of elements by wrapping it with the element you defined.


let's say we have lots of tables on our web page and the table have multiple columns now we want to make all table wrapped by a div with class table-responsive.

We can get the below jquery code on the insight document ready function to cover all tables with a defined div when the page loads.

                                                
                                                
                                                $(document).ready(function() {
    $('table').wrap('<div class="table-responsive"></div>');
});
                                                
                                            
let's see another example on button click we can see what is happening exactly.
                                                
                                                
                                                https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js

 <div class="main-content">

   <table>
    <tr>
      <th>Test table col</th>
    </tr>
  </table>

 </div>
 <button>Click to add</button>

 <script>
 $(document).ready(function(){
    //before added
    console.log($('.main-content').html());

    $("button").click(function(){
       $("table").wrap("<div class='table-responsive'></div>");
       //after added

       console.log($('.main-content').html());
    });
});
                                                
                                            

Leave a comment

  • ...
    tin

    Nice tutorial, please write more this type of content Thanks