Jquery wrapAllInner() ? -- Or wrapAll() applied internally?
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 rig开发者_C百科ht after it to get repeated twice. whut?
Thanks so much,
long time listener, first time caller
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.
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') ;
}
}) ;
精彩评论