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

2 Responses to “Check if an element exists in the DOM with jQuery”

  • ugg classic tall black size 9…

    Not something even compares to actual intercourse. But when price is generally an challenge, high-end imitation purses deliver clear-cut magnificence with real excellent. When buying for top rated degree on a limited budget, knock down purses are label…

  • google.com says:

    It’s going to be end of mine day, except before ending I am reading this fantastic post to
    increase my experience.

    Here is my web-site seo, google.com,

Leave a Reply

*