javascript removeChild 然后使用 insertBefore 将其替换为新文本

标签 javascript function modularity removechild

我想在外部 javascript 文件中创建一个函数,以便稍后重用(即,一个足够通用的模块化函数,可以在任何需要它的 javascript 中使用)。我想用纯 JavaScript 来完成此操作,而不是使用 jQuery 或innerHTML。

我希望这个模块化函数执行以下操作: 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
}

非常感谢你的帮助,杰森

最佳答案

哦,这更容易,因为这个函数本身已经存在:.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);
}

关于javascript removeChild 然后使用 insertBefore 将其替换为新文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12889239/

相关文章:

javascript - 从 head 调用 body 中定义的函数

ASP.NET 和火狐浏览器 : why doesn't clicking on a GridView ButtonField do anything?

javascript - onClick 事件返回代理对象而不是 ReactJX 中的事件处理程序对象

javascript - electro-forge:如何指定钩子(Hook)?

c - 如何重新启动程序而不保存其值 (C)

java - 如何使用Java 8的函数引用?

java - 如何使桌面应用程序模块化?

c++ - 模块化:是否使用接口(interface)?

python - igraph R 和 Python 中社区检测函数的不同结果

javascript - HTML元素插入DOM时是否有 "element ready"事件?