0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】要素の取得方法

Posted at

はじめに

Javascriptで要素を取得する際に使用するメソッドについてメモ。
それからメソッドを使用した際に返ってくる値について同じように見えるけど何が違うの?と疑問に感じたので備忘録として残します。

要素の取得

document.getElementById()

idを指定して要素を取得することができる。
指定したidが存在しなければnullを返す。

返り値:HTMLElementまたはnull

sample.html
<h1 id="title">タイトル</h1>
<span>サブタイトル</span>
sample.js
const title = document.getElementById('title');
console.log(title); // <h1 id="title">タイトル</h1>

const subTitle = document.getElementById('sub-title');
console.log(subTitle); // null

document.getElementsByClassName() / element.getElementsByClassName()

classを指定して要素を取得する。
特定の要素の配下から取得することも可能。

返り値:HTMLCollection

sample.html
<!-- ① -->
<p class="text">テキスト</p>
<p class="text">テキスト</p>
<!-- ② -->
<ul id="list">
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
</ul>
sample.js
// ① クラス名:textの要素を取得
const text = document.getElementsByClassName('text');
console.log(text); // HTMLCollection(2) [p.text, p.text]
// ② id:listの配下にあるクラス名:list-itemを取得
const list = document.getElementById('list');
const item = list.getElementsByClassName('list-item');
console.log(item); // HTMLCollection(3) [li.list-item, li.list-item, li.list-item]

for(let i = 0; i < item.length; i++) {
  console.log(item[i]);
  // <li class="list-item">テキスト</li>
  // <li class="list-item">テキスト</li>
  // <li class="list-item">テキスト</li>
}

document.getElementsByTagName() / element.getElementsByTagName()

タグを指定して要素を取得する。
特定の要素の配下から取得することも可能。

返り値:HTMLCollection

sample.html
<!-- ① -->
<p class="text">テキスト</p>
<p class="text">テキスト</p>
<!-- ② -->
<ul id="list">
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
</ul>
<ul>
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
</ul>
sample.js
// ① p要素を取得
const text = document.getElementsByTagName('p');
console.log(text); // HTMLCollection(2) [p.text, p.text]
// ② id:listの配下にあるli要素を取得
const list = document.getElementById('list');
const item = list.getElementsByTagName('li');
console.log(item); // HTMLCollection(3) [li.list-item, li.list-item, li.list-item]

for(let i = 0; i < item.length; i++) {
  console.log(item[i]);
  // <li class="list-item">テキスト</li>
  // <li class="list-item">テキスト</li>
  // <li class="list-item">テキスト</li>
}

document.querySelector() / element.querySelector()

idまたはclassを指定(CSSセレクタ)して、一致する最初の要素を取得する。
上記のメソッドとは違い、idとclassを記述する際はCSSで記述するのと同じように指定する。
特定の要素の配下から取得することも可能。

返り値:HTMLElement

sample.html
<p class="text">テキスト</p>
<p class="text">テキスト</p>

<ul id="list">
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
</ul>
sample.js
const text = document.querySelector('.text');
console.log(text); // <p class="text">テキスト</p>

const list = document.querySelector('#list');
console.log(list);
// <ul id="list"><li class="list-item">テキスト</li>・・・</ul>
const item = list.querySelector('.list-item');
console.log(item); // <li class="list-item">テキスト</li>

document.querySelectorAll() / element.querySelectorAll()

idまたはclassを指定(CSSセレクタ)して、一致するすべての要素を取得する。
idとclassを記述する際はCSSで記述するのと同じように指定する。
特定の要素の配下から取得することも可能。

返り値:NodeList

sample.html
<p class="text">テキスト</p>
<p class="text">テキスト</p>

<ul id="list">
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
  <li class="list-item">テキスト</li>
</ul>
sample.js
const text = document.querySelectorAll('.text');
//console.log(text); // NodeList(2) [p.text, p.text]

const list = document.querySelector('#list');
const item = list.querySelectorAll('.list-item');
//console.log(item); // NodeList(3) [li.list-item, li.list-item, li.list-item]

for(let i = 0; i < item.length; i++) {
  console.log(item[i]);
  // <li class="list-item">テキスト</li>
  // <li class="list-item">テキスト</li>
  // <li class="list-item">テキスト</li>
}

HTMLElement

HTMLElementとはHTMLドキュメントに含まれる要素。タグで囲まれた<html>,<head>,<body>,<div>・・・などの要素はHTMLElementとなる。

HTMLCollection

document.getElementsByClassNameメソッドdocument.getElementsByTagNameメソッドで取得できる配列風のオブジェクト。
インデックスを使用して要素にアクセスすることができる。

NodeList

document.querySelectorAllメソッドで取得できるノードの集合。こちらも配列風のオブジェクト。
HTMLCollectionと同じようにインデックスを使用して要素にアクセスすることができる。

配列風?

どちらもlengthプロパティを持ち、インデックス番号で要素にアクセスすることはできるため、配列風と言われている。

HTMLCollectionとNodeListの違い

一見同じのように見える2つだが、詳しく見ていくと違いが見えてくる。

HTMLCollectionは動的・NodeListは静的

下記コードはボタンをクリックすると新たな要素が追加(DOMが更新される)される仕組みになっている。
要素追加後のそれぞれの挙動を見てみると、HTMLCollectionは新たな要素も反映されているが、NodeListは要素追加前と変わらない状態になっている。

HTMLCollection:DOMが更新されると自動的に反映される
NodeList:DOMが更新されても反映されない

See the Pen getElementByとquerySelectorの違い by 引地澄佳 (@vqjkiggh-the-lessful) on CodePen.

使えるメソッドが違う

NodeListではforEachが使えるがHTMLCollectionでは使えない

sample.html
<ul id="myList">
    <li>アイテム1</li>
    <li>アイテム2</li>
</ul>
sample.js
/*
NodeList
*/
const nodeList = document.getElementById("myList").querySelectorAll("li");

nodeList.forEach((li) => {
  console.log(li);
  // <li>アイテム1</li>
  // <li>アイテム1</li>
});

/*
HTMLCollection
*/
const htmlCollection = document
  .getElementById("myList")
  .getElementsByTagName("li");

htmlCollection.forEach((li) => {
  console.log(li);
  // エラー:htmlCollection.forEach is not a function
});
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?