DOMメモ
DOM(Document Object Model)は ウェブページをJavaScriptで表現したもの であり、
「ウェブページとJavaScriptをつなぐ役割」を果たします。
言い換えると、JavaScriptで扱えるオブジェクトの集まり です。
documentオブジェクト
document
は DOMの世界へのエントリーポイント です。
Webページのあらゆるコンテンツを表現しており、多数の便利なプロパティやメソッドが用意されています。
要素の取得方法
古くからあるメソッド
document.getElementById('hero');
document.getElementsByTagName('button');
document.getElementsByClassName('highlight');
新しいセレクター系メソッド
単一の要素を取得:
document.querySelector('h2');
document.querySelector('#hero');
document.querySelector('.highlight');
複数の要素を取得:
document.querySelectorAll('li');
要素の操作
innerText / textContent の違い
document.querySelector('p').innerText
// 表示されているテキストのみを取得(改行など整形済み)
document.querySelector('p').textContent
// HTML内の改行や空白も含めて取得
要素の書き換え
document.querySelector('h1').innerText = '<i>Welcome!</i>';
// → タグは解釈されずそのまま文字列として表示される
属性の操作
- getAttribute
- setAttribute
const img = document.querySelector('img');
img.getAttribute('src'); // 現在の画像パス
img.setAttribute('alt', 'ファンタジー世界のドラゴン');
CSSの取得
getComputedStyle(document.querySelector('h1'));
→ CSSStyleDeclaration
オブジェクトが返る(多数のプロパティを確認可能)。
classList の活用
const firstStrong = document.querySelector('strong');
firstStrong.parentElement; // 親要素を取得
firstStrong.classList.add('active');
firstStrong.classList.remove('active');
firstStrong.classList.toggle('active');
DOMツリーの移動
const paragraph = firstStrong.parentElement;
paragraph.children; // 子要素のHTMLCollectionを取得
const heroImg = document.querySelector('.thumbnail');
heroImg.nextSibling; // 次のノード(テキストなども含む)
heroImg.nextElementSibling; // 次の要素ノード
要素の追加・削除
const newImg = document.createElement('img');
newImg.src = "https://picsum.photos/200";
// 追加
document.body.appendChild(newImg); // 末尾に追加
document.body.prepend(newImg); // 先頭に追加
paragraph.append(newImg); // 複数要素や文字列も追加可能
// 削除
paragraph.removeChild(newImg);
newImg.remove(); // 直接削除(新しい書き方)
まとめ
- DOMは JavaScriptとHTMLをつなぐ仕組み
-
document
オブジェクトから始まる - 要素取得は
querySelector
/querySelectorAll
が主流 - 要素の内容や属性、スタイルは自由に操作可能
- 親子関係や隣接要素をたどってDOMツリーを操作できる