$('elemId').length对我不起作用。
你需要在元素 id 之前放# :
$('#elemId').length
---^使用 vanilla JavaScript,您不需要哈希( # ),例如document.getElementById('id_here') ,但是在使用 jQuery 时,您需要将基于id哈希值放入目标元素,就像 CSS 一样。
尝试检查选择器的长度,如果它返回一些东西,那么元素必须存在,否则不存在。
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
试试这个:
if ($("#mydiv").length > 0){
// do something here
}如果 element 不存在,则 length 属性将返回零。