tags:

views:

866

answers:

5

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?

+10  A: 

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

$("#lblUpdateStatus").text("");
bang
+6  A: 

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

if ($('#lblUpdateStatus').length) {
    $("#lblUpdateStatus").text("");
}
Dan F
+1  A: 

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.

Tony L.
+4  A: 

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("");
Tomas Lycken
+1  A: 

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');
stoimen
Which is the same as if ($('#element_id').length) { console.log('the element with element_id exists in the DOM'); } (Essentially DanF's answer above.)
Nosredna