0

後で再利用できる外部のJavaScriptファイルに関数を作成したいと思います(つまり、必要なJavaScriptで使用できるほど一般的なモジュラー関数)。jQueryやinnerHTMLを使用せずに、純粋なJavaScriptでこれを実行したいと思います。

このモジュラー関数に次のことを実行させたい: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
}

助けてくれてありがとう、ジェイソン

4

1 に答える 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);
}
于 2012-10-15T04:34:20.243 に答える