勉強したことのメモ

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

  関連記事

Javascript / jQueryにて特定の要素内の文字数が〇文字以上の場合に丸める方法
Javascript / jQueryにて特定の要素内の文字数が〇文字以上の場合に丸める方法

サイトの特定の要素内の文字数が〇文字以上の場合に「コンテンツコンテ……」のように ...

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

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

テキストエリアを選択すると中身を全選択状態にする方法
テキストエリアを選択すると中身を全選択状態にする方法

テキストエリアやテキストボックスの中に文字が書いてあり、ドラッグをしなくても、そ ...

jquery.cookie.jsで「$.cookie is not a function」エラー
jquery.cookie.jsで「$.cookie is not a function」エラー

フロントエンド側でCookieを利用したい場合jquery-cookieを用いる ...

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

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