Although this has long been asked, it is still a problem (as of June 2015) in jQuery (v1.11.1). Here's my workaround that feels a little ... well, say, "special", but nonetheless works:
var $orig = $('p'); // some existing element var $wrap = $('<div>').css({border:'1px solid red'}); $wrap = $orig.wrap($wrap).parent(); //the object that is being wrapped is returned, so selecting its parent will get the wrapper. Re-setting that in the $wrap variable will retain the wrapper for reference $wrap.append('<p>SMOKE YOU</p>'); // this will now work
Note. The caveat is that the $wrap element can no longer be reused for packaging, as it now contains the $orig element. A workaround for this is to use add() another βspecialβ way:
var $orig = $('p'); // some existing element var $wrap = $('<div id="wrapper">').css({border:'1px solid red'}); $wrap = $wrap.add($orig.wrap($wrap.clone().empty()).parent()); //the object that is being wrapped is returned, so calling for its parent will return the wrapper. $wrap.append('<p>SMOKE YOU</p>'); // this will now work $wrap = $wrap.add( $('div.otherdiv').wrap($wrap.clone().empty()).parent()) console.log($wrap); //as you can see the $wrap variable now contains two divs $wrap.css({'border' : '1px solid blue'}); //this will now work on all wraps
This is not very clean code, but it works! See this script for a working example.
c_kick
source share