Code Snippet Submit one! Home » Code Snippets » jQuery » Check if Element ExistsCheck if Element Existsif ( $('#myElement').length > 0 ) { // it exists }
You don’t need the “> 0″, you can simply write:
if ( $('#myElement').length ) {
// it exists
}
No true, since jQuery always returns an object with length 0
it’s true. If element exists: length > 0, and condition is true.
If element not exosts: length = 0 and condition is false
Even easyest and reusable, you can define a function:
jQuery.fn.exists = function() { return this.length>0; };
And use it, anywhere, simple like this:
if ($(‘#myElemento).existe()) { … }
Better,
if($(element).size()){
// …
}
That’s not better at all.
jQuery#sizesimply returns thelengthproperty, so just save the function call and access thelengthproperty directly.nice tuto :P
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.