13
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

querySelectorAll はNodeListを返すので単なるif(hoge) で存在チェックできない

Last updated at Posted at 2019-10-30

JavaScript のファイル内で、対象のページにDOMが存在するか分からない時に、対象のDOMをquerySelector()した後でif(hoge) で存在チェックをすることがあります。
querySelector() の場合には戻り値がnullなのでこれでいいのですが、querySelectorAll() を使った時にほんの少しハマったので共有しておきます。

Chrome Developer Tool のコンソールで動作を確認してみます。

querySelector() のケース

image.png

マッチしないものを指定しているのでnullが返ってきて想定どおりです。

querySelectorAll() のケース

image.png

NodeList []が返ってきてます。これだと
if(temp) だとNodeListが空でもtruthyなので存在チェックになっていません。

というわけで存在判定には length を使って以下のように使えばよかったのでした。

image.png

13
4
2

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
13
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?