Check if element exists in jQuery
This question already has an answer here:
$('elemId').length
doesn't work for me.
You need to put #
before element id:
$('#elemId').length
---^
With vanilla JavaScript, you don't need the hash ( #
) eg document.getElementById('id_here')
, however when using jQuery, you do need to put hash to target elements based on id
just like 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
}
Try this:
if ($("#mydiv").length > 0){
// do something here
}
The length property will return zero if element does not exists.
链接地址: http://www.djcxy.com/p/2384.html上一篇: JQuery检查以查看是否显示Div
下一篇: 检查jQuery中是否存在元素