勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

jQueryにて特定のIDが存在するかチェックし分岐処理する方法

  jQuery JavaScript

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 JavaScript

  関連記事

jQueryでiframe内の要素を呼び出し
jQueryでiframe内の要素を呼び出し

jQueryでiframeで開いたbody内の内容が欲しかった。 ■jQuery ...

jQueryで要素を移動する方法のまとめ
jQueryで要素を移動する方法のまとめ

jQueryで要素を移動する際、insertBefore / insertAft ...

jQueryでUNIXタイムスタンプの取得
jQueryでUNIXタイムスタンプの取得

jQueryでUNIXタイムスタンプを取得したい場合、 $.now()だけで取得 ...

「jQuery.browser is undefined」エラーの対応方法
「jQuery.browser is undefined」エラーの対応方法

jQueryのプラグインを使っていて1.9以降だと「jQuery.browser ...

jQueryにて$.parseHTML()を用いてHTML文字列をDOMノードに変換する方法
jQueryにて$.parseHTML()を用いてHTML文字列をDOMノードに変換する方法

あるサイトのソースコードを拝見しているとjQueryで$.parseHTML() ...