NOTE开发笔记与题库FETCHED

jQuery 判断 id 或元素是否存在

我们可以通过呢 jQuery 的 length 属性判断 id 是否存在: 实例 [mycode3 type='js'] if ($('#myElement').length > 0) { // 存在 } [/mycode3] 尝试一下 » 也可以写成插件形式,如下,插件可以判断元素是否存在 实例 [mycode3 type='js'] $.fn.e..

更新于 2026/7/16

教程详情页默认 noindex。

我们可以通过呢 jQuery 的 length 属性判断 id 是否存在:

实例

if ($('#myElement').length > 0) { // 存在 }

尝试一下 »
也可以写成插件形式,如下,插件可以判断元素是否存在

实例

$.fn.exists = function(callback) { var args = [].slice.call(arguments, 1); if (this.length) { callback.call(this, args); } return this; }; // 使用方法 $('div.test').exists(function() { this.append('<p>存在!</p>'); }); ​