Posts Tagged ‘exists’

Check if an element exists in the DOM with jQuery

Need to check if an element exists in the page you have loaded using jQuery. It is very simple. The jQuery object encapsulates zero or more DOM elements, and allows us to interact with them in many different ways. Therefor, we can just use the length property to check if our jQuery object, that is returned by our selector query has one or several DOM elements attached to it.

Check if a specific element exists based on ID.

if($('#my-element').length) {
    // Action code goes here
}

Check if a specific or several elements exists based on CLASS.

if($('.my-element').length) {
    // Elment found
}

or

if($('.my-element').length != 0) {
    // Elements found
}

or

if($('.my-element').length > 0) {
    // Elements found
}

Remy Sharp have written an excellent post and recorded a screencast that explains this further on jQuery for Designers