2012-08-17 57 views
4

我試圖做同樣的事情/相同這樣一個問題: How to remove only the parent element and not its child elements in JavaScript?其內容替換父元素

<div> 
    This is some text here 
    <h2>This is more text</h2> 
</div> 

所有我想要的是去除H2標籤。結果應該是:

<div> 
    This is some text here 
    This is more text 
</div> 

假設我已經在H2元素:

所有的
if (parentElement.nodeName.toLowerCase() == "h2") { 
    //now what? I basically want to this: $.replaceWith(parentElement.innerText) 
    //just without jQuery 
} 
+1

得到h2元素的文本,並把它的變種。刪除整個h2並將文本放在那裏。 – 2619 2012-08-17 09:50:40

+0

可能的重複[如何在JavaScript中只刪除父元素而不是其子元素?](http://stackoverflow.com/questions/170004/how-to-remove-only-the-parent-element-and-不是它的子元素在JavaScript) – 2012-08-17 10:23:59

+0

我投票結束這個問題。如果你看看其他的答案,他們已經在純JavaScript中提供瞭解決方案。看例如:http://stackoverflow.com/a/176404/218196 – 2012-08-17 10:24:31

回答

4

假設變量h2準確地引用您想在採取行動的h2元素,我的第一個想法是:

var h2 = document.getElementsByTagName('h2')[0], 
    textnode = h2.firstChild; 

h2.parentNode.insertBefore(textnode,h2.nextSibling); 
h2.parentNode.removeChild(h2);​ 

JS Fiddle demo

要稍微更幹做,函數的做法可以是:

function unwrapH2(el) { 
    if (!el) { 
     return false; 
    } 
    else { 
     var textnode = el.firstChild, 
      elParent = el.parentNode; 

     elParent.insertBefore(textnode, h2.nextSibling); 
     elParent.removeChild(h2); 
    } 
} 

var h2 = document.getElementsByTagName('h2')[0]; 

unwrapH2(h2); 

JS Fiddle demo

調整上述響應給Felix克林的評論(見下文),並且還使用replaceChild()

function unwrapH2(el) { 
    if (!el) { 
     return false; 
    } 
    else { 
     var textnode = el.firstChild, 
      elParent = el.parentNode; 
     elParent.replaceChild(textnode,el); 
    } 
} 

var h2 = document.getElementsByTagName('h2')[0]; 

unwrapH2(h2); 

JS Fiddle demo

+1

'var textnode = h2.firstChild;'就足夠了。我也認爲你可以簡單地做'h2.parentNode.replaceChild(textnode,h2)'。 – 2012-08-17 10:02:23

+0

很快。完善! – 2012-08-17 10:03:41

+0

非常歡迎,我很高興得到了幫助! @Felix,當然;謝謝! =) – 2012-08-17 10:06:24

0

首先,jQuery的上手。它使你的生活更輕鬆。

在jQuery中,請執行下列操作:

var h2html = $('div h2').html(); 
$('div h2').remove(); 
$('div').append(h2html); 

編輯:

以上只有1個div和1 h2元素,它是在div的最後一個元素的作品。這只是一個簡單的例子。下面是代碼,使您的生活更加簡單:

$('div h2').each(function (x, y) { 
    $(this).replaceWith($(this).html()); 
});​ 
+0

如果OP想要使用jQuery,他可以只使用鏈接問題中的代碼。另外,你的代碼不正確。它用第一個'h2'元素的內容替換每個'div'的內容。它確實保留了'div'元素中現有的文本節點。 – 2012-08-17 10:03:31

+0

它確實讓我的生活更輕鬆,但對於一個按鈕和四行Javascript來說,鞭出整個圖書館是愚蠢的。 – 2012-08-17 10:04:15

+0

@FelixKling Ofcourse這不適用於超過1格+ h2。這只是爲了表明想法... – Hidde 2012-08-17 10:09:07

1

使用現代JS!

const h2 = document.getElementsByTagName('h2')[0]; 
h2.replaceWith(h2.firstChild); 

要代替所有的孩子代替,使用:

h2.replaceWith(...h2.childNodes); // or h2.children, if you don't want textNodes