Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an "exists" function for jQuery?

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?

like image 613
Jake McGraw Avatar asked Aug 27 '08 19:08

Jake McGraw


People also ask

Is exist in jQuery?

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.

What is '$' in jQuery?

$ 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.

How use contains in jQuery?

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).


1 Answers

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.

like image 178
Tim Büthe Avatar answered Oct 15 '22 10:10

Tim Büthe