How to check if an element exists in jQuery

[source language=“javascript“]
if ( $("#mydiv").length ){
// do something here
}
[/source]

Briefer again…

[source language=“javascript“]
if ( $("#mydiv")[0] ){
// do something here
}
[/source]

via http://aaronrussell.co.uk/legacy/check-if-an-element-exists-using-jquery/

2 Kommentare zu „How to check if an element exists in jQuery

  1. I personally find this to be the best:

    if( $('#mydiv').length ) { /* do stuff */ }

    length is better since it returns an

    int

    (0 if no elements found). The other approach returns undefined if no elements found.

Kommentar verfassen