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