![](/img/trans.png)
[英]How to replace text in HTML Node without disturbing other child nodes?
[英]How can I replace a tag without disturbing the content?
我只是想刪除一個html標記(打開和關閉),而不會干擾內容。
例如,鑒於此標記...
var temp =
<span id="myspan1">
<span id="myspan2" class="new">
hello world !</span>
</span>
我想去這個...
var newcontent =
<span id="mySpan1">
hello world !
</span>
請幫助我解決這個問題在jQuery中。
我認為jQuery有一個未unwrap
。 由於unwrap
會刪除父對象,因此我們需要獲取#myspan2
的內容,以使#myspan2
成為要刪除的父對象, 最后以#myspan1
為父對象 。
$('#myspan2').contents().unwrap();
為了進一步闡明為什么unwrap
比做html
更好的原因是,當您執行.html()
,它僅檢索從當前元素派生的DOM的字符串表示形式。 它不會獲取這些后代附帶的處理程序和數據。 因此,如果使用該HTML字符串重新創建DOM,它將確實重新創建DOM,但不再具有附加到這些后代的處理程序和數據 。
只要在myspan1
范圍內沒有其他內容,這應該可以工作:
$("#myspan1").html($("#myspan2").html());
它將myspan1
span的內容替換為myspan1
的內容, myspan2
有效地刪除了標簽。 對於給定的示例,它可以工作,但是如果myspan1
除了myspan2
之外還有其他內容,它將失敗。
試試下面的代碼
$('#myspan1').html($('#myspan2').html())
$('#myspan1').html($('#myspan2').html());
嘗試
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.