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

Typically in JavaScript I do something like the below to verify an element does exist:

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

But, using jQuery - how can I do the same type of thing?

Answers


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("");
}

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

$("#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("");

From jQuery 1.4 onwards you can use $.contains().

var test = $("<div>");
$.contains(window.document, test[0]);  // false

$("body").append(test);
$.contains(window.document, test[0]);  // true

I wrote a post about that on my blog

if ( $('#element_id').length > 0 )
   console.log('the element with element_id exists in the DOM');

If HTML string can be passed into $(), you can use parent.length:

$('<div>').length // 1, but it not exist on page

but

$('<div>').parent().length // 0

Need Your Help

What is an unsigned char?

c++ c char

In C/C++, what an unsigned char is used for? How is it different from a regular char?