All blog posts, code samples and downloads licensed under Apache License 2.0.

Test if DOM element exists in jQuery

Oliver Busse on 12/27/2013 06:02:28 PM CET, filed under CSJS 

Just stumbled upon how to test if an element exists in your DOM using jQuery. Struggled with several approaches such as typeof, undefined and even used a try-catch to check if any attempt to access a property of a non-existing element may cause an error.

Forget all about it or everything you may find on Stackoverlow etc. Use this on instead as it works!

var elementToTest = $(".selectorOfMyElement");
if(elementToTest.length > 0){
    // element is in the DOM
} else {
    // element is not part of the DOM

As easy as it can be when you know it Winken

Tagged with javascript jquery dom