Mathieu Mahé
Mathieu Mahé

Reputation: 2746

What is the best way to check if a selector exists?

With JQuery, to check if a selector exists, I do something like :

if ($(selector).length > 0) { ... }

But I suppose it's maybe not the best way because I just want to know if a selector exists, not how many. Is there a way to stop the search at the first occurrence found for optimization reason ?

Thank you!

EDIT: To clarify : I'd like to avoid the "length" method because it checks in all the DOM. I just want to stop when one occurrence is found

Upvotes: 9

Views: 15339

Answers (3)

Exception
Exception

Reputation: 8389

Use this,

if( $('#idofelement'))  or
if( $('.classname')  )

Upvotes: -4

biziclop
biziclop

Reputation: 14616

In theory you could append :first to your query to limit results ( http://api.jquery.com/first-selector/ ), but it would actually make your query slower, because it prevents jQuery from using the native querySelectorAll() function of modern browers.

Upvotes: 1

Rob W
Rob W

Reputation: 349142

There's no more efficient method to let jQuery stop after finding a matching element.
It's not even possible in Vanilla ("pure") JavaScript to limit document.getElementsByTagName("p") to match only one element, without having a worse performance.

Upvotes: 8

Related Questions