How to verify an element exists in the DOM using jQuery?

The thing is that the jQuery will only do the requested action if the element exists :-), so you only need:

$("#lblUpdateStatus").text("");

The get method returns the matched DOM elements:

if($("#lblUpdateStatus").get(0)){
    $("#lblUpdateStatus").click(function () { ... });
}

but I am not sure if it is a fast method.


$ returns an array of matching elements, so check the length property and you're good to go

if ($('#lblUpdateStatus').length) {
    $("#lblUpdateStatus").text("");
}

I see no reason to use jQuery just for the sake of it. the $('#lblUpdateStatus') will basically go straight to document.getElementById('lblUpdateStatus'), as the selector has an anchor in it, so you're not really gaining anything. Also, for just checking if the DOM object exists, wrapping it in a jQuery object will create quite a lot of overhead.

On the other hand, if just changing the text property of the object is what you want to do, you don't need to check for its existence if you use jQuery.

if (document.getElementById('lblUpdateStatus')) {
    $("#lblUpdateStatus").text("");
}

will do the exact same thing as having just

$("#lblUpdateStatus").text("");

Tags:

Jquery