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?

【初心者向け】querySelectorとquerySelectorAllの違いを整理してみた

0
Posted at

はじめに

JavaScriptでDOMを取得するときに
querySelectorquerySelectorAll の違いが曖昧だったので整理しました。

メソッド 取得できるもの
querySelector 最初の1つだけ
querySelectorAll 条件に一致する全部

① querySelector

一致する要素の「最初の1つ」だけ取得します。
.item が3つあっても、最初の1つだけ返ります。

const item = document.querySelector(".item");
console.log(item);

② querySelectorAll

一致する要素を「全部」取得します。
.item が3つあれば、3つとも取得できます。

const items = document.querySelectorAll(".item");
console.log(items);

昔は下記を使っていたようですが上記2個で代用できるようです。
(CSSセレクタで指定できるので扱いやすい!)

getElementById()

getElementsByClassName()

getElementsByTagName()

注意点:配列ではない

querySelectorAll() が返すのは NodeList です。

配列っぽいですが、本物の配列ではありません。

console.log(items[0]); // 1つ目は取得できる
0
0
0

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?