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
}
Is there a more elegant way to approach this? Perhaps a plugin or a function?
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
}
Is there a more elegant way to approach this? Perhaps a plugin or a function?
You don't have to check if it's greater than
0
like$(selector).length > 0
,$(selector).length
it's enough and a elegant way to check the existence of elements. I don't think that is worth to write a function only for this, if you want to do more extra things, yes.I stumbled upon this question and i'd like to share a snippet of code i currently use:
And now i can write code like this -
It might seem a lot of code, but when written in CoffeeScript it is quite small:
You could use this:
size()
counts the number of elements returned by the selectorI see most of the answers here are not accurate as they should be, they check element length, it can be OK in many cases, but not 100%, imagine if number pass to the function instead, so I prototype a function which check all conditions and return the answer as it should be:
This will check both length and type, Now you can check it this way:
The reason all of the previous answers require the
.length
parameter is that they are mostly using jquery's$()
selector which has querySelectorAll behind the curtains (or they are using it directly). This method is rather slow because it needs to parse the entire DOM tree looking for all matches to that selector and populating an array with them.The ['length'] parameter is not needed or useful and the code will be a lot faster if you directly use
document.querySelector(selector)
instead, because it returns the first element it matches or null if not found.However this method leaves us with the actual object being returned; which is fine if it isn't going to be saved as variable and used repeatedly (thus keeping the reference around if we forget).
In some cases this may be desired. It can be used in a for loop like this:
If you don't actually need the element and want to get/store just a true/false, just double not it !! It works for shoes that come untied, so why knot here?