「JavaScript」createElementでテキストボックスを作成する

2022年3月16日

環境
Google Chrome 99.0.4844.51

書式
1.inputタグ作成
const 変数名 = document.createElement(“input");
2.setAttributeで属性を作成します
変数名.setAttribute(“type", “text");
変数名.setAttribute(“maxlength", 値);

使用例

<!DOCTYPE html>
<html>
<body>
<div id="cft"></div>

<p><input type="button" value="追加" onclick="addBtn()" /></p>
<script>
  function addBtn() {
    const inputEle = document.getElementById("cft");
    // input要素テキストボックスの追加
    if (!cft.hasChildNodes()) {
      //inputタグ作成
      const inputA = document.createElement("input");
      //inputタグの属性を設定します
      inputA.setAttribute("type", "text");
      //maxlengthを設定します
      inputA.setAttribute("maxlength", "8");
      //sizeを設定します
      inputA.setAttribute("size", "10");
      //valueを設定します
      inputA.setAttribute("value", "東京");
      
      //子ノードinputAを追加します
      inputEle.appendChild(inputA);
    }
  }
</script>

</body>
</html>

実行結果

「追加」ボタンを押すと、テキストボックスを作成します。
下記コードが生成されます
<input type="text" maxlength="8" size="10" value="東京">

 

JavaScript

Posted by arkgame