Reputation: 19
Am just wanted to remove an html tag (both opening and closing) without disturbing the content.
For example, given this markup...
var temp =
<span id="myspan1">
<span id="myspan2" class="new">
hello world !</span>
</span>
I want to get to this...
var newcontent =
<span id="mySpan1">
hello world !
</span>
Please help me resolve with this in jquery.
Upvotes: 1
Views: 95
Reputation: 119827
I think jQuery's got an unwrap
. Since unwrap
removes the parent, we need to get the contents of #myspan2
to make #myspan2
the parent to be removed, ending up with #myspan1
being the parent.
$('#myspan2').contents().unwrap();
To further clarify why unwrap
is better than doing html
is that when you do .html()
, it only retrieves a string representation of the DOM descending from the current element. It does not fetch the handlers and data that come with those descendants. Thus, if you recreate the DOM with that HTML string, it does recreate the DOM properly but does not anymore have the handlers and data that were attached to those descendants.
Upvotes: 7
Reputation: 1930
if you are looking to assign the content of a immediate child element to parent element, you can use this
$("#myspan2").parent().html($("#myspan2").html());
Upvotes: 0
Reputation: 388316
Try
var temp = '<span id="myspan1"><span id="myspan2" class="new">hello world !</span></span>';
var $t = $(temp);
$t.find('.new').contents().unwrap();
console.log($t[0].outerHTML)
Upvotes: 0
Reputation: 69250
This should work, as long as you have no other content in the myspan1
span:
$("#myspan1").html($("#myspan2").html());
It replaces the content of the myspan1
span with the contents of myspan2
, effectively removing the tag. For the example given it works, but it would fail if you have other content inside myspan1
besides myspan2
.
Upvotes: 1