Check block existence by jQuery

How do I know if there is a block with class "media" on the page?

if(<div class="media"></div> exist in current page){
//then do something
}

This code doesn't work:

if($(".media")){ //do }

You need to check if ($('.media').length) .

$(...) returns a jQuery object, which will always be "truthy", even when empty.
However, if it's empty, its length property will be 0 , which is "falsy".

You can also be more explicit and write if ($('.media').length > 0) .


if ($(".media").length > 0) { ... }

if($(".media").length){ //do }
链接地址: http://www.djcxy.com/p/83700.html

上一篇: 如果页面上存在DIV,则将CSS添加到其他DIV

下一篇: 通过jQuery检查块的存在