「JavaScript」createElementでラジオボタンを追加する
環境
Google Chrome 99.0.4844.51
書式
1.inputタグ作成
const 変数 = document.createElement(“input");
変数の属性(type、name、id、value)を指定します
2.labelタグ作成
const 変数 = document.createElement(“label");
使用例
<!DOCTYPE html>
<html>
<body>
<div id="cft"></div>
<input type="button" value="追加" onclick="addBtn()" />
<script>
function addBtn() {
const fc = document.getElementById("cft");
// 要素の追加
if (!fc.hasChildNodes()) {
const inputA = document.createElement("input");
//input要素の属性を設定type name id value
inputA.type = "radio";
inputA.name = "city";
inputA.id = "city";
inputA.value = "大阪";
//テキストノード作成
const txtCity = document.createTextNode("大阪");
//タグlabel作成
const lab = document.createElement("label");
lab.htmlFor = inputA.id;
//子ノードを追加
lab.appendChild(inputA);
lab.appendChild(txtCity);
fc.appendChild(lab);
}
}
</script>
</body>
</html>
実行結果
「追加」ボタンを押すと、ラジオボタンが表示されます。 下記ソースタグが作成されます <label for="city"><input type="radio" name="city" id="city" value="大阪">大阪</label>