[jQuery Tip] Check Elements

Here are a couple of jQuery tips to deal with elements.


1. Count Immediate Child Elements

jQuery selectors return an array of elements. You can simply use the “length” property of it.

var count = $("#mydiv > section").length;

The size() method is deprecated.


2. Check if an Element Exists

jQuery does not provide “exists()” method. But the “length” property will be your friend.

if ($("#mydiv").length > 0) {
} else {
  alert("Not Exist");

It is simple and also one of the most useful techniques.


3. Check if an Element is Visible

Another useful trick is to check the visibility of an Element.

if ($("#mydiv").is(":visible")) {
} else {

:visible is a jQuery extension and not part of the CSS specification.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s