tags:

views:

27

answers:

2

I'm trying to insert an opening <div class="container"> after <body> and a closing </div> before </body>

I'd like for there to be a function like wrapAll() that would apply internally, on the html() of an element. Something like wrapAllInner() would be great.

I've tried:

1) $('body').html().wrapAll('<div class="container"></div>');

which didn't work at all. $("body").html().wrapAll is not a function. weird.

2) $('body').children().wrapAll('<div class="container"></div>');

which for some reason caused the js to get repeated twice. It even caused an alert() I placed right after it to get repeated twice. whut?

Thanks so much,

long time listener, first time caller

+3  A: 

Just a .wrapInner() to wrap the contents of the single <body> element works here, like this:

$('body').wrapInner('<div class="container"></div>');

You can test it out here.


The reason .html() doesn't work is .html() without parameters gets the HTML inside the <body> element, a string, which doesn't have any jQuery functions.

Nick Craver
Thanks so much! Can't believe I missed that function.
CloudMagick
A: 

Alternatively, you could insert your div at the start of the body, then loop through the direct children in the body and move them inside the div:

$('body').prepend('<div class="container"></div>') ;
$('body').children().each() function() {
    if(!$(this).hasClass('container')) {
        $(this).prependTo('div.container') ;
    }
}) ;
Gus
There's no need for all this moving around, `.wrapInner()` does exactly what the OPs after here.
Nick Craver