[JavaScript]appendChildで画像を追加する
書式
var element = document.createElement(tagName[, options]);
引数 tagName
生成される要素の型を特定する文字列。生成される要素の nodeName は tagName の値で初期化されます。
使用例
<div id="show"></div>
<script>
// idに一致するDOM要素
const cft = document.getElementById("show");
//imgで指定されhtml要素を生成
const imgEle = document.createElement("img");
// src指定
imgEle.src = "./images/test.png";
// 幅
imgEle.width = 100;
//高さ
imgEle.height = 100;
//cssText
imgEle.style.cssText = "margin-right:30px";
// divに要素を追加
show.appendChild(imgEle);
</script>
実行結果
imagesディレクトリに「test.png」を追加する