How can I check the existence of an element in jQuery?
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
<
The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript
:
if (document.getElementById('element_id')) {
// Do something
}
It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.
And it is better than the alternative of writing your own jQuery
function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists()
function is something inherent to jQuery. JavaScript
would/should be understood by others editing your code, without increased knowledge debt.
NB: Notice the lack of an '#' before the element_id
(since this is plain JS, not jQuery
).