[JavaScript]appendChildで画像を追加する

2021年10月25日

書式
var element = document.createElement(tagName[, options]);
引数 tagName
生成される要素の型を特定する文字列。生成される要素の nodeName は tagName の値で初期化されます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
<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」を追加する

JavaScript

Posted by arkgame