2

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 }
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
James
  • 42,081
  • 53
  • 136
  • 161

5 Answers5

7

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).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
4

You can use .length to check for existance

   if ($(".media").length)
    {//do something}
Blowsie
  • 40,239
  • 15
  • 88
  • 108
3

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.

Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84
3
if ($(".media").length > 0) { ... }
Xion
  • 22,400
  • 10
  • 55
  • 79
3
if($(".media").length){ //do }
Andy Rose
  • 16,770
  • 7
  • 43
  • 49