コンテンツにスキップ

JavaScript/Element

出典: フリー教科書『ウィキブックス(Wikibooks)』


JavaScriptのElementオブジェクト

[編集]

はじめに

[編集]

HTMLドキュメントの中で、あらゆる要素はブラウザによってElementオブジェクトとして扱われます。Elementオブジェクトは、DOMツリーにおける個々の要素を表し、要素の属性、内容、スタイルなどを操作するためのプロパティとメソッドを提供します。この章では、Elementオブジェクトの基本から応用までを詳しく解説します。

Elementオブジェクトの取得

[編集]

JavaScriptでElementオブジェクトを取得するには、いくつかの方法があります。最も一般的なのは、document.getElementById()メソッドを使う方法です。

// IDを使って要素を取得する
const element = document.getElementById('myElement');

// CSS セレクタを使って最初の要素を取得する
const firstElement = document.querySelector('.myClass');

// CSS セレクタに一致するすべての要素を取得する
const allElements = document.querySelectorAll('div.container');

Elementオブジェクトの基本プロパティ

[編集]

Elementオブジェクトには、様々な基本プロパティがあります。以下に代表的なプロパティをまとめました。

プロパティ名 説明
id 要素のID属性の値 element.id = 'newId';
className 要素のclass属性の値(文字列) element.className = 'btn active';
classList 要素のクラス名リスト(DOMTokenList) element.classList.add('highlight');
tagName 要素のタグ名(大文字) console.log(element.tagName); // "DIV"
innerHTML 要素内のHTML element.innerHTML = '新しい内容';
textContent 要素内のテキスト(すべての子要素のテキストを含む) element.textContent = '新しいテキスト';
style 要素のインラインスタイル element.style.color = 'red';

属性の操作

[編集]

Elementオブジェクトでは、HTML属性を操作するためのメソッドが提供されています。

// 属性値の取得
const src = imgElement.getAttribute('src');

// 属性の設定
buttonElement.setAttribute('disabled', 'true');

// 属性の存在確認
const hasAlt = imgElement.hasAttribute('alt');

// 属性の削除
linkElement.removeAttribute('target');

// data-*属性の操作
const value = divElement.dataset.value; // data-value属性の取得
divElement.dataset.status = 'active';   // data-status属性の設定

要素の内容操作

[編集]

要素の内容を操作するには、いくつかの方法があります。

// HTMLを使った内容の設定(パースされる)
element.innerHTML = '<strong>太字テキスト</strong>';

// テキストとしての内容設定(エスケープされる)
element.textContent = '<strong>これはタグとして解釈されません</strong>';

// 要素をクリア
element.innerHTML = '';
// または
while (element.firstChild) {
  element.removeChild(element.firstChild);
}

子要素の操作

[編集]

Elementオブジェクトを使って、子要素を追加、削除、置換することができます。

// 新しい要素の作成
const newElement = document.createElement('div');
newElement.textContent = '新しい要素';

// 子要素として追加
parentElement.appendChild(newElement);

// 特定の位置に挿入
parentElement.insertBefore(newElement, referenceElement);

// 最新のAPIを使った挿入
parentElement.append(newElement);  // 末尾に追加
parentElement.prepend(newElement); // 先頭に追加
referenceElement.before(newElement); // 前に挿入
referenceElement.after(newElement);  // 後に挿入

// 子要素の削除
parentElement.removeChild(childElement);
// または
childElement.remove();

// 子要素の置換
parentElement.replaceChild(newElement, oldElement);
// または
oldElement.replaceWith(newElement);

要素のスタイル操作

[編集]

Elementオブジェクトのstyleプロパティを使って、インラインスタイルを操作できます。

// インラインスタイルの設定
element.style.color = 'blue';
element.style.fontSize = '16px';
element.style.backgroundColor = '#f0f0f0';

// 複数のスタイルをまとめて設定
Object.assign(element.style, {
  display: 'flex',
  justifyContent: 'center',
  marginTop: '20px'
});

// 計算されたスタイルの取得
const computedStyle = window.getComputedStyle(element);
const fontSize = computedStyle.fontSize;

クラス操作

[編集]

要素のクラスを操作するには、classListプロパティを使うのが最も便利です。

// クラスの追加
element.classList.add('highlight');

// 複数のクラスを追加
element.classList.add('active', 'visible');

// クラスの削除
element.classList.remove('disabled');

// クラスの存在確認
const isHighlighted = element.classList.contains('highlight');

// クラスの切り替え(あれば削除、なければ追加)
element.classList.toggle('selected');

// 条件付きクラス切り替え
element.classList.toggle('expanded', isExpanded); // 第2引数がtrueなら追加、falseなら削除

要素の寸法と位置

[編集]

Elementオブジェクトからは、要素の寸法と位置に関する情報を取得できます。

// 要素のサイズと位置を取得
const rect = element.getBoundingClientRect();
console.log(`幅: ${rect.width}px, 高さ: ${rect.height}px`);
console.log(`左端からの距離: ${rect.left}px, 上端からの距離: ${rect.top}px`);

// スクロール関連
element.scrollTop = 100; // 垂直スクロール位置を設定
const scrollHeight = element.scrollHeight; // スクロール可能な高さを取得

// 要素を表示範囲内にスクロール
element.scrollIntoView({
  behavior: 'smooth',
  block: 'start'
});

イベント処理

[編集]

Elementオブジェクトにイベントリスナーを追加して、ユーザーの操作などに反応させることができます。

// イベントリスナーの追加
element.addEventListener('click', function(event) {
  console.log('要素がクリックされました');
  console.log('クリック位置:', event.clientX, event.clientY);
});

// オプション付きのイベントリスナー
element.addEventListener('mouseover', handleMouseOver, { once: true });

// イベントリスナーの削除
element.removeEventListener('click', handleClick);

// イベントの発火(トリガー)
const clickEvent = new Event('click');
element.dispatchEvent(clickEvent);

要素の作成と変更(実践例)

[編集]

以下は、JavaScriptを使って動的に要素を作成し、変更する例です。

// ユーザーカードを作成する関数
function createUserCard(user) {
  // カード要素の作成
  const card = document.createElement('div');
  card.className = 'user-card';
  
  // ユーザー名
  const name = document.createElement('h3');
  name.textContent = user.name;
  
  // メールアドレス
  const email = document.createElement('p');
  email.textContent = user.email;
  
  // ステータスバッジ
  const badge = document.createElement('span');
  badge.className = 'badge';
  badge.textContent = user.active ? 'アクティブ' : '非アクティブ';
  badge.style.backgroundColor = user.active ? '#4caf50' : '#f44336';
  
  // 要素の組み立て
  card.appendChild(name);
  card.appendChild(email);
  card.appendChild(badge);
  
  // クリックイベントの追加
  card.addEventListener('click', function() {
    showUserDetails(user.id);
  });
  
  return card;
}

// 使用例
const user = {
  id: 1,
  name: '山田太郎',
  email: 'yamada@example.com',
  active: true
};

const userCard = createUserCard(user);
document.getElementById('user-container').appendChild(userCard);

Elementオブジェクトのトラバース

[編集]

DOM内を移動して他の要素にアクセスする方法です。

// 親要素へのアクセス
const parent = element.parentElement;

// 子要素へのアクセス
const firstChild = element.firstElementChild;
const lastChild = element.lastElementChild;
const children = element.children; // HTMLCollection

// 兄弟要素へのアクセス
const nextSibling = element.nextElementSibling;
const previousSibling = element.previousElementSibling;

// すべての子要素を処理
for (let child of element.children) {
  console.log(child.tagName);
}

要素の検証と比較

[編集]

要素が特定の条件に一致するかどうかを検証したり、要素同士を比較したりする方法です。

// 要素がセレクタにマッチするか確認
const matches = element.matches('.active.highlighted');

// 最も近い祖先要素を検索
const closestHeader = element.closest('header');

// 要素の比較
const areEqual = element1 === element2;

// 要素が他の要素の子孫かどうかを確認
const isDescendant = parentElement.contains(childElement);

まとめ

[編集]

Elementオブジェクトは、JavaScriptでHTMLドキュメントを操作する際の中心的な存在です。この章では、Elementオブジェクトの基本的なプロパティからはじまり、属性操作、内容の変更、スタイリング、イベント処理など、幅広い機能について解説しました。これらの知識を活用することで、動的でインタラクティブなWebページを作成することができます。

附録

[編集]

静的アクセサ

[編集]

静的メソッド

[編集]

継承関係

[編集]

ObjectEventTargetNodeElement

Elementのインスタンスプロパティ

[編集]
Element.prototype [ Symbol.toStringTag ]
Element.prototype [ Symbol.unscopables ]

Elementのインスタンスアクセサ

[編集]

Nodeのインスタンスプロパティ

[編集]
Node.prototype.ATTRIBUTE_NODE
Node.prototype.CDATA_SECTION_NODE
Node.prototype.COMMENT_NODE
Node.prototype.DOCUMENT_FRAGMENT_NODE
Node.prototype.DOCUMENT_NODE
Node.prototype.DOCUMENT_POSITION_CONTAINED_BY
Node.prototype.DOCUMENT_POSITION_CONTAINS
Node.prototype.DOCUMENT_POSITION_DISCONNECTED
Node.prototype.DOCUMENT_POSITION_FOLLOWING
Node.prototype.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
Node.prototype.DOCUMENT_POSITION_PRECEDING
Node.prototype.DOCUMENT_TYPE_NODE
Node.prototype.ELEMENT_NODE
Node.prototype.ENTITY_NODE
Node.prototype.ENTITY_REFERENCE_NODE
Node.prototype.NOTATION_NODE
Node.prototype.PROCESSING_INSTRUCTION_NODE
Node.prototype.TEXT_NODE
Node.prototype [ Symbol.toStringTag ]

Nodeのインスタンスアクセサ

[編集]
get Node.prototype.baseURI
get Node.prototype.childNodes
get Node.prototype.firstChild
get Node.prototype.isConnected
get Node.prototype.lastChild
get Node.prototype.nextSibling
get Node.prototype.nodeName
get Node.prototype.nodeType
get Node.prototype.nodeValue
get Node.prototype.ownerDocument
get Node.prototype.parentElement
get Node.prototype.parentNode
get Node.prototype.previousSibling
get Node.prototype.textContent

Nodeのインスタンスメソッド

[編集]
Node.prototype.appendChild()
Node.prototype.cloneNode()
Node.prototype.compareDocumentPosition()
Node.prototype.constructor()
Node.prototype.contains()
Node.prototype.getRootNode()
Node.prototype.hasChildNodes()
Node.prototype.insertBefore()
Node.prototype.isDefaultNamespace()
Node.prototype.isEqualNode()
Node.prototype.isSameNode()
Node.prototype.lookupNamespaceURI()
Node.prototype.lookupPrefix()
Node.prototype.normalize()
Node.prototype.removeChild()
Node.prototype.replaceChild()

EventTargetのインスタンスプロパティ

[編集]
EventTarget.prototype [ Symbol.toStringTag ]

EventTargetのインスタンスアクセサ

[編集]

EventTargetのインスタンスメソッド

[編集]
EventTarget.prototype.addEventListener()
EventTarget.prototype.constructor()
EventTarget.prototype.dispatchEvent()
EventTarget.prototype.removeEventListener()