要素の取得方法
ページ内のHTML要素にアクセスするためには、目的に応じた複数のメソッドが提供されています。
// IDを使って単一の要素を取得
const targetElement = document.getElementById('header');
// タグ名で複数の要素を取得(HTMLCollectionが返る)
const paragraphs = document.getElementsByTagName('p');
// クラス名に基づいて要素を取得
const items = document.getElementsByClassName('item');
// CSSセレクタで最初に一致する要素を取得
const firstBlock = document.querySelector('.content-block');
// 複数の一致要素をNodeListとして取得
const allLinks = document.querySelectorAll('nav ul li a');
コンテンツと属性の更新
取得した要素の内容や属性を動的に変更することが可能です。
// HTMLを含む内部コンテンツの書き換え
targetElement.innerHTML = '<strong>更新されたコンテンツ</strong>';
// テキストのみを安全に設定(HTMLはエスケープされる)
targetElement.innerText = 'テキストだけが変更されます';
// 属性の設定または更新
const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');
link.setAttribute('target', '_blank');
// スタイルの直接操作
link.style.backgroundColor = '#007bff';
link.style.padding = '8px 12px';
link.style.borderRadius = '4px';
ノードの生成とDOMツリーの変更
新しい要素を作成して文書構造に追加したり、不要な要素を削除できます。
// 新しい要素ノードの作成
const newSection = document.createElement('section');
newSection.className = 'dynamic-section';
newSection.textContent = 'この要素はJavaScriptで生成されました';
// 親要素に子を追加
const container = document.getElementById('container');
container.appendChild(newSection);
// 子要素を特定して削除
const childToRemove = document.getElementById('temp-element');
if (childToRemove && childToRemove.parentNode) {
childToRemove.parentNode.removeChild(childToRemove);
}
クラスリストの操作
要素のクラス属性に対して追加・削除・トグルなどの操作が簡単にできます。
const panel = document.querySelector('.panel');
// クラスの追加
panel.classList.add('visible');
// 特定のクラスを削除
panel.classList.remove('hidden');
// 状態に応じてクラスを切り替え
panel.classList.toggle('expanded');
// クラスが存在するか確認
if (panel.classList.contains('active')) {
console.log('パネルはアクティブです');
}
属性の読み取りと確認
既存の属性値を取得したり、属性の有無をチェックできます。
// href属性の値を取得
const url = link.getAttribute('href');
// data-* 属性の利用例
const userId = element.getAttribute('data-user-id');
const config = element.getAttribute('data-config');
イベントリスナの管理
ユーザーの操作に応じて処理を実行するために、イベントハンドリングが不可欠です。
function handleClick() {
alert('ボタンがクリックされました!');
}
const button = document.getElementById('action-btn');
button.addEventListener('click', handleClick);
// 捕捉フェーズを使用したリスナ登録(稀に必要)
button.addEventListener('click', handleCapture, true);
// 同じ関数参照を使ってイベントを解除
button.removeEventListener('click', handleClick);
注意点として、removeEventListener を使用する際は、登録時と同じ関数オブジェクトと同じ useCapture 値が必要です。無名関数を使うと削除できなくなるため、名前付き関数または変数に代入した関数を使うのが推奨されます。