2013-06-03 62 views
0

欲換或更換第一個div且p是在一個div稱爲條目內容的第一個div:裹一個div

<div class="entry-content"> 
<div><div id="wrap">lala</div></div> 
<p><script type="text/javascript">window.location = "http://"</script></p> 
</div> 

或最佳的輸出將是(包裹物和替換):

<div class="entry-content"> 
<div id="wrap">lala</div> 
<script type="text/javascript">window.location = "http://"</script> 
</div> 

謝謝你的幫助!

+0

'.entry內容div'不是有效的ID。你爲什麼認爲你可以使用'getElementById'來看起來像一個選擇器?無論如何,它看起來像**要刪除**第一個'div'和'p'元素,但保留其內容,是否正確?包裝是不同的。 –

+0

看看下面的答案。由於您沒有提供HTML的「之前」版本,因此我不確定您真正想要做什麼。如果這沒有幫助,請讓我知道並更新您的問題,並更好地描述您的問題。 –

回答

1

它看起來像你想刪除元素,但保留其內容。如果你想稱之爲「解包」。

這可以用一個小的DOM操作來完成:

function unwrap(element) { 
    // insert all the element's children *after* the element itself 
    var parent = element.parentNode; 
    var children = element.childNodes; 
    var before = element.nextSibling; 

    // reverse iteration always inserting the previous sibling before 
    // the next one 
    for (var i = children.length - 1; i > -1; i--) { 
     before = parent.insertBefore(children[i], before); 
    } 

    // remove the element 
    parent.removeChild(element); 
} 

然後,所有你需要做的就是傳遞給要刪除的功能元素的引用。

DEMO

如果你真的想雖然更換元素,那麼你就必須所有子節點移動到新的元素,並用新的替換舊的元素。我調用函數「重新包裝」在這裏(因爲「替換」並不表示該內容被複制):

function rewrap(element, new_element) { 
    // append all the element's children to the new element 
    while (element.firstChild) { 
     new_element.appendChild(element.firstChild); 
    } 

    // replace old element with new 
    element.parentNode.replaceChild(new_element, element); 
} 

DEMO