简体   繁体   中英

jQuery wrap a div around a massive block of HTML

I've searched .wrap() , .append() , .wrapall() , and .insertAfter() and haven't found solutions. I would like to take a new div and wrap it around a block of html. I have no access to the HTML so I need to use jQuery.

The .insertAfter() function was ideal, but unfortunately it closes the html tags automatically.

The root of the problem is that I need to center two separate div s that I have no access over their HTML.

$(function () {  
    $('<div id="centerContainer">').insertAfter('#header');
    $('</div><!-- centerContainer -->').insertAfter('#footer');
});

That's not how DOM functions, .insertAfter() adds elements to the DOM not strings in that way, you should select all the elements and then call .wrapAll() on the returned collection.

Assuming( based on the posted code ) all the elements between the #header and #footer elements( if fact their siblings ) should be wrapped with another element you can use .nextUntil() for selecting next siblings of the #header until the #footer element and then call .wrapAll() on the returned collection:

$('#header').nextUntil('#footer').wrapAll('<div id="centerContainer"></div>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM