JavaScriptで要素が存在するかどうか調べてみます。
サンプルコード
調べ方はいくつか種類があるようですが、jQueryを使わない場合と、jQueryを使う場合から2種類を試してみます。
HTML
<div class="hoge"></div>
.hogeが存在するかどうかを試してみます。
JavaScript
// パターン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になります。
【参考サイト】
コメントが承認されるまで時間がかかります。