ノードの作成・挿入・削除 - Javascript

ノードの作成

document.createElement("要素名");

テキストノードの作成

document.createTextNode("テキスト");

ノードの挿入

要素の最後の子ノードとして引数のノードオブジェクトを挿入します

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <div id="box">

  </div>
</body>
</html>

script.js

window.onload = function(){
  let ele = document.createElement("h1"); // h1 タグの生成
  let txtnode = document.createTextNode("Hello, World"); // h1 タグで表示するテキスト
  ele.appendChild(txtnode); // テキストを h1 タグに挿入

  let box = document.getElementById("box");
  box.appendChild(ele); // h1 タグを html に挿入
};

ノードの削除

ノードの子ノードを削除します。

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <div id="parent">
    <h1 id="child">Hello, World</h1>
  </div>
</body>
</html>

script.js

window.onload = function(){
  let par = document.getElementById("parent"); 
  let ch = document.getElementById("child");

  par.removeChild(ch);
};

サンプル - リストを作成

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
</head>
<body>
  <div id="box">
    
  </div>
</body>
</html>

script.js

window.onload = function(){
  let ul = document.createElement("ul");

  for(let i = 1; i < 4; i++){
      let li = document.createElement("li");
      let li_txt = document.createTextNode("リスト" + i);
      li.appendChild(li_txt);
      ul.appendChild(li);    
  };

  let box = document.getElementById("box");
  box.appendChild(ul);
};

サンプル - label input:text

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>sample</title>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="box">
  </div>
  
</body>
</html>

script.js

window.addEventListener('load', function(){
  let box = document.getElementById("box");
  let ele_p = document.createElement("p");

  let ele_label = document.createElement("label");
  ele_label.setAttribute("for", "name");

  let ele_input = document.createElement("input");
  ele_input.setAttribute("id", "name");
  ele_input.setAttribute("type", "text");
  let name_txt = document.createTextNode("名前");

  ele_label.appendChild(name_txt);
  ele_label.appendChild(ele_input);

  ele_p.appendChild(ele_label);
  box.appendChild(ele_p);
});