How to check if an element exists on the page using jQuery?
Hello everyone! I just started learning jQuery and ran into a problem. I have code that should hide an element with the class `.my-block`, but if this element is not on the page, an error is printed to the console.
Here is my code:
```javascript
$('.my-block').hide();
```
When the element is missing, everything breaks. I tried writing it like this:
```javascript
if ($('.my-block')) {
$('.my-block').hide();
}
```
But this doesn't work because `$('.my-block')` always returns a truthy value, even if there are no elements. I read that in jQuery you need to check the length of the collection, but I'm not sure how to do it correctly.
Please tell me how to properly check if an element exists on the page before performing any actions with it? I'm interested specifically in the jQuery way, without pure JavaScript.
No answers yet.
Log in to leave an answer
Blogs
Asynchronous Programming in Go: A Complete Guide with Examples
GraphQL API with Swift: A Step-by-Step Practical Tutorial
Android 9 HTTP and HTTPS: How to Configure All Networks in 2025
Go Community: A Guide to Conferences, Blogs, and Resources for Developers