jQuery - how to test if selector matches anything?

2020-02-13 09:27发布

Say I have the following:

$('#foo')

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

2条回答
Bombasti
2楼-- · 2020-02-13 10:00

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
查看更多
贼婆χ
3楼-- · 2020-02-13 10:06
if ($('#foo').length > 0) {

    // do things
}

should do it

查看更多
登录 后发表回答