Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 449
Mathieu Mahé Avatar asked Nov 09 '11 17:11

Mathieu Mahé


1 Answers

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.

like image 149
Rob W Avatar answered Jan 02 '23 07:01

Rob W