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?
In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements.
Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not.
Answer: Use the jQuery . length Propertylength property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists in DOM. Here's an example that displays an alert on button click if the specified element exists.
$
returns an array of matching elements, so check the length property and you're good to go
if ($('#lblUpdateStatus').length) { $("#lblUpdateStatus").text(""); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With