javascriptjquerydrupal-7wrapall

jQuery wrapAll wraps content twice


I am working with Drupal views where I have to wrap the table with div tag with class. I did something like this in jQuery:

jQuery('table.views-table.table').wrapAll("<div class='table-responsive'></div>");

This wraps the content nicely at first screen load, like:

<div class="table-responsive">
<table class="views-table cols-5 table">.....

But I am also using Ajax to sort the table, so, when I sort the tables clicking sorting options the wrapAll() seems to wrap the content twice, like:

<div class="table-responsive">
<div class="table-responsive">
<table class="views-table cols-5 table">....

What shall I do to wrap the table only once with div even after using the Ajax sorting?

There is a similar question here, but I didn't understand how he fixed the issue.

I have also done the following, which also didn't work:

jQuery('elements....').wrap('elements....').unwrap('elements....').wrap('elements....'); 

but with no avail.


Solution

  • I fixed this with simple if statement to check the length, like:

    if(jQuery('.table-responsive').length == 0) {
        jQuery('table.views-table.table').wrap('<div class="table-responsive"> </div>');
    }