I'm looking for a technique using JQuery to remove an html tag (both opening and closing) without disturbing the content.
For example, given this markup...
<div id="myDiv">
Leave My Content alone!
</div>
I want to get to this...
<span id="mySpan">
Leave My Content Alone!
</span>
What I've tried:
I thought about $("#myDiv").remove or $("#myDiv").replaceWith, but both of them destroy the contents of the tag.
As always, your assistance is appreciated!
The easiest way to do this would be to do something like this:
$("#myDiv").replaceWith('<span id="mySpan">' + $("#myDiv").html() + "</span>");
However, that falls apart when you realize that you'll lose all event subscribers on any elements inside your <div />
. A better way to do this is to move the contents to a new <span />
tag just before the <div />
tag, then remove the <div />
, like this:
var yourDiv = $("#myDiv");
var yourSpan = $('<span id="mySpan"></span>');
yourDiv.before(yourSpan);
yourSpan.append(yourDiv.children());
yourDiv.remove();
This will "change" the wrapping tag without losing the actual elements inside of your <div />
tag. All event subscribers should remain on any elements inside of the <div />
.
What I would suggest is that you save the innerHTML value to a string, then you can replace or remove and add the new element, then set the innerHTML of the new value.
Another solution would be to go to the parent of the element you want to replace, and change the innerHTML property, replacing the <div>
and </div>
with <span>
and </span>
.
This one is a bit trickier, esp since you will need to make certain that if you have multiple divs within the innerHTML that you replace just the one of interest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With