javascript setAttributeで属性を作成する
- 2021.01.09
- javascript
- javascript

javascriptで、setAttributeを使用して、属性を作成するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
setAttribute使い方
setAttributeを使用すると、属性を作成することが可能です。
1 |
要素.setAttribute("属性名", "値"); |
setAttribute使い方
1 2 3 4 5 6 7 8 9 10 11 12 |
/* html */ <img id="main" src="https://mebee.info/wp-content/uploads/2019/08/mebee_logo.png" /> /* javascript */ 'use strict'; const elm = document.getElementById('main'); elm.setAttribute("width", "164"); elm.setAttribute("height", "50"); |
実行結果は、指定したhtml要素に、width属性とheight属性が追加されていることが確認できます。

また、以下のコードを、
1 2 3 4 |
const elm = document.getElementById('main'); elm.setAttribute("width", "164"); elm.setAttribute("height", "50"); |
document.getElementByIdの省略して、簡潔に記述することもできます。
1 2 |
main.setAttribute("width", "164"); main.setAttribute("height", "50"); |
サンプルコード
以下は、
「属性追加」ボタンをクリックして、img要素を作成してから、属性を追加するだけの
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> </head> <script> const hoge = () => { const elm = document.createElement("img"); elm.setAttribute("src", "https://mebee.info/wp-content/uploads/2019/08/mebee_logo.png"); elm.setAttribute("width", "128"); elm.setAttribute("height", "64"); sample.appendChild(elm); } window.onload = () => { add.onclick = () => { hoge() }; } </script> <body> <div class="container mx-auto my-56 w-64 px-4"> <div id="sample" class="flex flex-col justify-center"> <button id="add" class="bg-gradient-to-r from-blue-400 via-green-500 to-green-500 text-white py-2 px-4 rounded-full mb-3 mt-4"> 属性要素追加 </button> </div> </div> </body> </html> |
属性が追加されていることが確認できます。

-
前の記事
Django エラー「1366, “Incorrect string value:」が発生した場合の対処法 2021.01.08
-
次の記事
React.js ライブラリ「react-inner-image-zoom」を使って画像をZOOMさせる 2021.01.09
コメントを書く