要素が存在するかどうか調べる

JavaScriptで要素が存在するかどうか調べてみます。

サンプルコード

調べ方はいくつか種類があるようですが、jQueryを使わない場合と、jQueryを使う場合から2種類を試してみます。

HTML

1
<div class="hoge"></div>

.hogeが存在するかどうかを試してみます。

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// パターン1
if(document.getElementsByClassName('hoge').length) {
    console.log("document.getElementsByClassName('hoge').length の結果: true");
} else {
    console.log("document.getElementsByClassName('hoge').length の結果: false");
}
 
// パターン2
if(document.querySelector('.hoge')) {
    console.log("document.querySelector('.hoge') の結果: true");
} else {
    console.log("document.querySelector('.hoge') の結果: false");
}
 
$(function() {
    // パターン3
    if($('.hoge')[0]) {
        console.log("$('.hoge')[0] の結果: true");
    } else {
        console.log("$('.hoge')[0] の結果: false");
    }
 
    // パターン4
    if($('.hoge').length) {
        console.log("$('.hoge').length の結果: true");
    } else {
        console.log("$('.hoge').length の結果: false");
    }
});

パターン1と2がjQueryを使わない方法、パターン3と4がjQueryを使う方法になります。
要素が存在するかを調べるデモページ

パターン1のgetElementsByClassName()は、指定したclass名の全要素を配列に近いオブジェクトで返すので、その要素数をlengthで調べています。

パターン2のquerySelector()は要素が見つからなかった場合にnullを返します。
getElementById()などでも同様ですが、nullの場合はfalse、nullでない場合はtrueになります。

パターン3は指定した要素のうち0番目の要素を調べていて、見つからない場合はundefinedを返します。

パターン4はパターン1と同じで、要素数を調べて0の場合はfalse、1以上の場合はtrueになります。
 

【参考サイト】

 

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2025年4月
 12345
6789101112
13141516171819
20212223242526
27282930