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>
リファレンス
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/length
関連記事
-
-
jQueryで要素を移動する方法のまとめ
jQueryで要素を移動する際、insertBefore / insertAft ...
-
-
PHPとajaxでチャットの作成
■ソース ・index.php <? error_reporting(E_ ...
-
-
日付の範囲指定用プラグイン「DateRangePicker」の利用方法
日付型のデータを検索する際に開始・終了日のテキストボックスを用意し、それぞれにタ ...
-
-
jQueryで偶数or奇数行に任意のClassを付与する方法
tableタグの1行目を除く偶数もしくは奇数行のtrタグに任意にClassを指定 ...
-
-
jQueryでAjax通信したデータをPHPで受け取り、zip化したファイルをダウンロードさせる方法
jQueryのAjaxで何らかのデータをPHP側に送信し、PHP側で当該データを ...