A little dab'll do yaCode Snippets Code Snippets > jQuery > Check if Element Exists Submit one!Check 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
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