HTMLを操作する
DOM(Document Object Model)…プログラム(JavaScipt)からHTMLファイルを操作する仕組み
- 要素の指示
-
- document.getElementsByTagName('tagName');
- タグ名で指示される要素配列
- document.getElementsByClassName('ClassName');
- クラス名で指示される要素配列
- document.getElementsByName('name');
- [name]属性値で指示される要素配列
- document.getElementById('id');
- [id]属性値で指示される要素
※id属性のみhtml内でユニークな値
- 要素中のコンテンツ
-
- コンテンツの取得
-
変数 = 要素.innerHTML
<p id="copy">中身のテキスト</p>
<script> let content = document.getElementById("copy").innerHTML; document.write(content); </script>
中身のテキスト
- コンテンツの書き換え
-
要素.innerHTML = '書き換え内容';
<p id="rewrite">書き換わるよ</p>
<script> document.getElementById("rewrite").innerHTML = '書き換わった!'; </script>
書き換わるよ
- フォーム要素の値取得
- 変数 = 要素.value
- 要素のスタイル属性設定
-
- 要素.style = 'スタイルシート設定';
<p id="changeStyle">背景色</p>
<script> document.getElementById("changeStyle").style = 'background:gold;'; </script>
背景色
- 要素.style.プロパティ = '値';
<p id="changeBackground">背景色</p>
<script> document.getElementById("changeBackground").style.background = 'silver'; </script>
背景色
- 要素.style = 'スタイルシート設定';
- 要素の属性設定
-
要素.setAttribute(属性名,属性値);
<p id="changeAttribute">背景色</p>
<script> document.getElementById("changeAttribute").setAttribute('style','background:pink;'); </script>
背景色
- 要素のクラス属性設定
-
- 指定したクラス名が含まれているか(条件文の中で使う)
- 要素.classList.contains('クラス名');
- 指定したクラスを削除する
- 要素.classList.remove('クラス名');
- 指定したクラスを付加する
- 要素.classList.add('クラス名');