Check block existence by jQuery
How do I know if there is a block with class "media" on the page?
if(<div 开发者_JS百科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)
.
You can use .length to check for existance
if ($(".media").length)
{//do something}
if ($(".media").length > 0) { ... }
if($(".media").length){ //do }
One way to do it is:
if ($("div.media").length > 0) {
// Then do something.
}
Hint: use the tag name div
before the class .media
because it is more efficient.
精彩评论