特定のセレクターでオブジェクトが見つからない場合にjQueryがエラーをスローしない特定の理由はありますか?
例えば:
$("#content").css("color","red");
ここでは、id "content" を持つ要素はありませんが、エラーでも何もしていません。
特定のセレクターでオブジェクトが見つからない場合にjQueryがエラーをスローしない特定の理由はありますか?
例えば:
$("#content").css("color","red");
ここでは、id "content" を持つ要素はありませんが、エラーでも何もしていません。
一致が見つからない場合にゼロ要素を持つ戻り要素コレクションの jQuery セレクターは、それがどのように設計されているかです。プロパティを使用length
して、要素を取得したかどうかを確認できます
if($('yourselector').length)
{
//You got one or more elements
}
else
{
//You haven't got any element.
}
定義
jQuery.fn.extend({
notEmpty: function (atLeast) {
const len = atLeast || 1;
if (this.length < len)
throw `unable to find ${len} element with selector :
'${this.selector}'. ${this.length} element is found.`;
return this;
}
});
使用する
let el = $(".at_least_one_element_selector").notEmpty();
let el = $(".at_least_5_element_selector").notEmpty(5);