Checking if an element exists with jQuery Checking if an element exists with jQuery

You want to do some conditional processing depending on if an item or items exist in your DOM (Document Object Model). By default, jQuery doesn't have a function that performs this; however, there is a very simple way to extend jQuery to do so.


Extending jQuery with an Exists function

Let's get right to the code:


// Extend jQuery with an "exists" function
jQuery.fn.exists = function() {
return this.length;
};
// Call the exists function
if ($("#myId").exists()) {
// Do something because it exists
}

Some people might consider it overkill to extend jQuery to perform such a simple statement, but sometimes readability is just as important. This same code could be altered as follows and would accomplish the same thing:


// Call the exists function
if ($("#myId").length) {
// Do something because it exists
}

To perform subsequent checks on other objects, it is basically the same amount of typing; however, by calling an exists function, my code is more readable without the need to add a comment because it's quite clear what is being done via a descriptive function name.

jQuery is extremely simple to extend and create custom functions that can then be applied to any jQuery selector – in this case checking if an item exists!

Published on Mar 19, 2019

Tags: extend | JavaScript | jQuery Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.