StackOverflowNewbie
StackOverflowNewbie

Reputation: 40633

jQuery - how to test if selector matches anything?

Say I have the following:

$('#foo')

I'd like to know if that selector matches anything. How do I test for this?

Upvotes: 8

Views: 3467

Answers (2)

David Wick
David Wick

Reputation: 7095

if ($('#foo').length > 0) {

    // do things
}

should do it

Upvotes: 24

cheeken
cheeken

Reputation: 34655

Use a Javascript Console to see what your method call returns. Type your command into the console, and then hit enter.

Shortcuts to open a JS console:

  • Chrome: Ctrl + Shift + I, then click the Console tab
  • Firefox: Ctrl + Shift + J

Upvotes: -2

Related Questions