Remove a HTML tag but keep the innerHtml
$('b').contents().unwrap();
This selects all <b>
elements, then uses .contents()
to target the text content of the <b>
, then .unwrap()
to remove its parent <b>
element.
For the greatest performance, always go native:
var b = document.getElementsByTagName('b');
while(b.length) {
var parent = b[ 0 ].parentNode;
while( b[ 0 ].firstChild ) {
parent.insertBefore( b[ 0 ].firstChild, b[ 0 ] );
}
parent.removeChild( b[ 0 ] );
}
This will be much faster than any jQuery solution provided here.
You can also use .replaceWith()
, like this:
$("b").replaceWith(function() { return $(this).contents(); });
Or if you know it's just a string:
$("b").replaceWith(function() { return this.innerHTML; });
This can make a big difference if you're unwrapping a lot of elements since either approach above is significantly faster than the cost of .unwrap()
.