powered by Slim Framework
enhanced by Nesbot.com

jQuery: Checking if an element exists

Published on Jan 2, 2012 by Jamie Munro

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.

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.

Summary


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!

Tags: Javascript | jquery

<- HTML: Absolute Position…when it's relative  Home MVC 3: Compile Views During Project Build -> 
blog comments powered by Disqus