示例:
var $doesNotYetExistInTheDOM = $('<span/>'); // create new jQuery element
// outside of the DOM
var $doesExistInTheDOM = $('span'); // selected element from the DOM
有没有办法检查 DOM 中是否存在 jQuery 选定对象?
答案 0 :(得分:2)
试试这个:
$('span').length // if exists it return > 0 or 0
如果您想使用任何特定id
或class
进行检查,请尝试:
$('span.some').length
或
$('span#some').length
使用您的变量:
var $doesNotYetExistInTheDOM = $('<span/>');
$(document,$doesNotYetExistInTheDOM).length
var $doesExistInTheDOM = $('span');
$(document,$doesExistInTheDOM ).length
jQuery有一个名为 .size()
的方法(但首选.length
)
使用:强>
$('span.some').size()
$('span#some').size()
var $doesNotYetExistInTheDOM = $('<span/>');
$(document,$doesNotYetExistInTheDOM).size()
答案 1 :(得分:1)
您可以通过尝试在文档中找到它来进行检查:
!!$(document).find($doesNotYetExistInTheDOM).length // false
!!$(document).find($doesExistInTheDOM).length // true