LoginSignup
30
32

More than 5 years have passed since last update.

selectorの存在確認に便利な`$(selector).exists()`を実装しておく

Last updated at Posted at 2014-03-13

概要

これ、なにかと便利です。便利というか可読性がよい。

jQuery.fn.exists = function(){return Boolean(this.length > 0);}

複数個生成したくないDOMを追加する際にvalidateするときとかに使う。
formがsubmitされた際のalert表示を複数個追加したくなかったので、こういうのほしかったのです。

サンプル

jQuery.fn.exists = function(){return Boolean(this.length > 0);}

// <中略>

if ($(selector).exists()) {
  // selectorが既に存在してた場合の処理
}

その他

追記1(2014/03/13 13:52)

これ、以下でも実現できるし、意味的にはこっちの記述も良い気がするけど、いろいろと冗長...
処理的に冗長だし、条件によっては一部結果に不備が出るようです。詳細は以下のコメントを参照。
(2014/03/14 10:40追記)

jQuery.fn.exists = function(){
  return Boolean($("body:has(" + this.selector + ")").length > 0);
}

参考

30
32
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
32