JavaScript replaceChildメソッドで要素をボタンに置き換えるサンプル

環境
Windows 10 Home 64bit
Google Chrome 106.0.5249.103

構文
1.親ノード.replaceChild(新しいノード, 古い子ノード);
replaceChildは、Nodeインターフェースのメソッドです。
古い子ノードを新しいノードで置き換えます。
replaceChild() は Node 要素のメソッドで、この(親)ノードの中の子ノードを置き換えます。
Node.replaceChild() メソッドは指定ノードの子ノードを別のノードに置き換えます。

2.let element = document.createElement(tagName[, options]);
tagName 生成される要素の型を特定する文字列です。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
options
省略可能な ElementCreationOptions オブジェクトで、 is という名前のプロパティをひとつ持ち、
その値は前に customElements.define() を使用して定義したカスタム要素の名前です。
options 省略可能な ElementCreationOptions オブジェクトで、 is という名前のプロパティをひとつ持ち、 その値は前に customElements.define() を使用して定義したカスタム要素の名前です。
options
省略可能な ElementCreationOptions オブジェクトで、 is という名前のプロパティをひとつ持ち、
その値は前に customElements.define() を使用して定義したカスタム要素の名前です。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<p id="ma">テスト:
<span id="cft">置換ボタンを押して下さい</span>
</p>
<input type="button" value="置換" onclick="chgbtn()">
<script>
function chgbtn(){
// ボタンを作成
const tt = document.createElement("input");
// ボタンを作成
tt.setAttribute("type","button");
tt.setAttribute("value","詳細");
tt.setAttribute("id","cft");
const tb = document.getElementById("cft");
const pb = document.getElementById("ma");
// 文字をボタンに置き換え
pb.replaceChild(tt,tb);
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <p id="ma">テスト: <span id="cft">置換ボタンを押して下さい</span> </p> <input type="button" value="置換" onclick="chgbtn()"> <script> function chgbtn(){ // ボタンを作成 const tt = document.createElement("input"); // ボタンを作成 tt.setAttribute("type","button"); tt.setAttribute("value","詳細"); tt.setAttribute("id","cft"); const tb = document.getElementById("cft"); const pb = document.getElementById("ma"); // 文字をボタンに置き換え pb.replaceChild(tt,tb); } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<p id="ma">テスト:
      <span id="cft">置換ボタンを押して下さい</span>
</p>
<input type="button" value="置換" onclick="chgbtn()">


<script>
function chgbtn(){
   // ボタンを作成
    const tt = document.createElement("input");
    // ボタンを作成
    tt.setAttribute("type","button");
    tt.setAttribute("value","詳細");
    tt.setAttribute("id","cft");
    
    const tb = document.getElementById("cft");
    const pb = document.getElementById("ma");
    // 文字をボタンに置き換え
    pb.replaceChild(tt,tb);
}
</script>

</body>
</html>

実行結果
「置換」ボタンを押すとreplaceChildメソッドでボタンに置き換えます。

JavaScript

Posted by arkgame