Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: How can I replace a tag without disturbing the content?

Tags:

jquery

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!

like image 784
JohnFx Avatar asked Nov 08 '09 02:11

JohnFx


2 Answers

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 />.

like image 59
Dan Herbert Avatar answered Oct 03 '22 09:10

Dan Herbert


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.

like image 23
James Black Avatar answered Oct 03 '22 09:10

James Black