2012-10-15 40 views
0

我想創建一個外部JavaScript文件中的一個函數,我可以稍後重用(即模塊化函數足夠通用,可用於任何需要的JavaScript)。我想用純JavaScript來做到這一點,而不是使用jQuery或innerHTML。javascript removeChild然後用新文本替換這個使用insertBefore

我想這種模塊化功能做到以下幾點: 1)刪除子 2)的元素與新的子值替換這個孩子

例如說你有這個代碼:

<p id="removeMe">This text needs to be removed</p> 
<p id="nextPara">This is the paragraph that follows the replaced paragraph</p> 

所以我需要:

1) parentNode.removeChild(removeMe); 
    2) var replacementParagraph = document.createElement('p'); 
    3) var replacementParagraphText =document.createTextNode("This is the replacementParagraph text); 
    4) replacementParagraph.appendChild(replacementParagraphText); 

現在我只需要弄清楚如何寫模塊化的功能有點像貝爾流量:

function removeReplace (parameter, parameter) { 
    1) remove the child of the paragraph with the id of "removeMe" 
    2) use insertBefore(newText, nextPara) to replace the child that was removed in step 1 
} 

非常感謝你的幫助,傑森

回答

2

哦,這是非常容易,因爲這個功能本身已經存在:.replaceChild()。其實你已經得到了算法,你只需要用javascript編寫它:

function replaceElementByParagraph(id, text) { 
    var toremove = document.getElementById(id); 
    if (!toremove) // in case no element was found: 
     return false; // abort 
    var para = document.createElement('p'); 
    para.appendChild(document.createTextNode(text)); 
    return toremove.parentNode.replaceChild(para, toremove); 
} 
+0

謝謝Bergi。這似乎是我需要的,但我不能得到它的工作 – HoppedUpDesigns

+0

[Worksforme](http://jsfiddle.net/HfzPd/)? – Bergi