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.
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.
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
.
试试下面的代码
$('#myspan1').html($('#myspan2').html())
$('#myspan1').html($('#myspan2').html());
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)
如果您希望将直接子元素的内容分配给父元素,则可以使用此方法
$("#myspan2").parent().html($("#myspan2").html());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.