Reputation: 103
How could one go about unwrapping an element, without removing the parent element?
For example, if I had the following
<strong>Some text <span>and some more text.</span> And a little more.</strong>
Is there a javascript or jquery way to unwrap the span, resulting in
<strong>Some text </strong><span>and some more text</span><strong>And a little more.</strong>
I can use jquery's unwrap to simply remove the strong tag from the span, but that results in the text outside of the span also losing the tag.
Upvotes: 2
Views: 338
Reputation: 33618
var span = $("strong span").detach();
var strong = $("strong").contents().wrap("<strong/>").end().append(span).contents().unwrap();
var span = $("strong span").detach();
var strong = $("strong").contents().wrap("<strong/>").end().append(span).contents().unwrap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong>hello all<span>hello</span> this text has no span </strong>
Upvotes: 0
Reputation: 207900
Here's one way to do it:
$("strong").contents().filter(function () {
return (this.nodeType==3)
}).wrap('<strong/>').parent().unwrap();
This results in:
<strong>Some text </strong><span>and some more text.</span><strong> And a little more.</strong>
Upvotes: 4
Reputation: 3716
As requested, here's the method I was talking about. I used jQuery and broke it up into more lines than necessary for simplicity, but you can condense/use built in JS functions if you prefer. Play around with it here: https://jsfiddle.net/vmge8a7j/
var strongElem = $("strong");
var spanElem = $("span");
$("span").remove();
$("#parent").append(spanElem);
Upvotes: 1