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?
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements.
$ is pretty commonly used as a selector function in JS. In jQuery the $ function does much more than select things though. You can pass it a selector to get a collection of matching elements from the DOM. You can pass it a function to run when the document is ready (similar to body.
jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0
means false
, everything else true
. So you could write:
if ($(selector).length)
You don't need that >0
part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With