jQueryにて特定のIDが存在するかチェックし分岐処理する方法
jQueryにて特定のIDが存在するかチェックし分岐処理したいというケースがあった。ClassであればhasClass()を使うんだけどIDの場合はどうしたらいいのか知らなかったので調べた結果をメモ。
対応方法
ソースコード
<div id="test_area">
<button id="test_btn">button</button>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function(){
if( $(`#test_btn`).length ){
console.log(`存在します。`);
}else{
console.log(`存在しません。`);
}
});
</script>
<div id="test_area">
<button id="test_btn">button</button>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function(){
if( $(`#test_btn`).length ){
console.log(`存在します。`);
}else{
console.log(`存在しません。`);
}
});
</script>
<div id="test_area"> <button id="test_btn">button</button> </div> <script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $(function(){ if( $(`#test_btn`).length ){ console.log(`存在します。`); }else{ console.log(`存在しません。`); } }); </script>
リファレンス
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/length
関連記事
-
-
jQueryにて$.parseHTML()を用いてHTML文字列をDOMノードに変換する方法
あるサイトのソースコードを拝見しているとjQueryで$.parseHTML() ...
-
-
jQueryの日付&時間のピッカー(bootstrap-datetimepicker)について
日付のピッカーはよく見るけど、時間のピッカーはあまり見ないので、普通のセレクトメ ...
-
-
tableのtd内にあるcheckboxのクリック範囲を拡大させ、チェック時に親要素であるtdにCSSを割り当てる方法
tableのtd内にcheckboxを設置し、td部分をクリックすることでche ...
-
-
jQueryにてCookieを取り扱う「jquery-cookie」プラグインの利用方法
jQueryでcookieを簡単に取り扱える「jquery-cookie」プラグ ...
-
-
jQuery Nice Selectを特定ページのみ無効にする方法
bootstrap系のテンプレートデザインを使用したサイトを構築中に、セレクトメ ...