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?
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?
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("");
document.getElementById('lblUpdateStatus') might be easier to read (I don't think so, but I guess it's a matter of habit), but you risk running into null reference errors if you try to do something with whatever that statement returns, and there is no such element on the page. The jQuery method will in that case just silently do nothing (which might or might not be what the OP intended...)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');