Update: Well, I made a nice post about extending jQuery with an unwrapInner function, but I discovered that the same thing can be done by using jQuery's
Starting with this HTML:
jQuery has a wrap and wrapAll which can be removed by using the unwrap function. But it only targets the parents of the selected element. What about wrapInner? It doesn't have a method to remove it. So I put together this small extension which does just that.
So say we start with this HTML:
replaceWith()
function... Starting with this HTML:
<div class="test">the span from around the red text can be removed by using the
<span class="red">
red text
</span>
<div class="green">
green text
</div>
</div>
replaceWith()
function as follows: // unwrap red textSo you can pretty much ignore the rest of this post =(
$('.test').find('.red')
.replaceWith( $('.test .red').contents() );
jQuery has a wrap and wrapAll which can be removed by using the unwrap function. But it only targets the parents of the selected element. What about wrapInner? It doesn't have a method to remove it. So I put together this small extension which does just that.
So say we start with this HTML:
<div class="test">To remove that span from around "some text", we just call the unwrapInner code below
<span>some text</span>
</div>
// unwrapInner functionYou can include a selector to target a specific element
jQuery.fn.extend({
unwrapInner: function(selector) {
return this.each(function() {
var t = this,
c = $(t).children(selector);
if (c.length === 1) {
c.contents().appendTo(t);
c.remove();
}
});
}
});
// examplesNote that the one issue with this function is when there are multiple children to be unwrapped, it will add the unwrapped content to the end. For example, with this HTML:
$("div").unwrapInner(); // remove immediate child
$("div").unwrapInner("span"); // remove immediate child if it's a span
$("div").unwrapInner("span.inner"); // remove all immediate children of class '.inner'
<div class="test">We want to unwrap
<span class="red">
red text
</span>
<div class="green">
green text
</div>
</div>
span.red
, so we use $(".test").unwrapInner(".red");but we get this result:
<div class="test">Check out this demo:
<div class="green">
green text
</div>
red text
</div>