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



Question:

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!


Solution:1

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


Solution:2

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.


Solution:3

Take a look at the example of the replaceWith method. I know you said you knew about it, but I think you were using it in the wrong way. Here's a snippet of what it mentions:

$("button").click(function () {    $(this).replaceWith("<div>" + $(this).text() + "</div>");  });  

Though you may want to use $(this).html() instead of $(this).text(). Still recommend you look at the page though. Click the buttons to see that it really is doing what it says it'll do :) Sorry if I misunderstood your question.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »