Finding out if an element exists with jQuery and/or Javascript

If your looking to find out if an element your about to select using ID, class and/or element type exists or not then you can do this using JavaScript, or if your implementing jQuery you may as well keep your code concise and use the jQuery method explained further down.

JavaScript

So here is an example of how this is done in JavaScript:

if (document.getElementById("elementid")) {
	//element with this id exists
}

if (document.getElementsByName("firstname")[0]) {
	//an element with this name exists
}

if (document.getElementsByClassName("classname")[0]) {
	//an element with this class name exists
}

//So IE has the getElementsByClassName
//By: Dean Williams http://dean.resplace.net
onload=function(){
	if (document.getElementsByClassName == undefined) {
		document.getElementsByClassName = function(className)
		{
			var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
			var allElements = document.getElementsByTagName("*");
			var results = [];

			var element;
			for (var i = 0; (element = allElements[i]) != null; i++) {
				var elementClass = element.className;
				if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
					results.push(element);
			}

			return results;
		}
	}
}

For the last one, getElementsByClassName there is not an implementation in IE so there is a function to create it if it does not exist!

jQuery

If however you wish to do this with jQuery it is even simpler, here are some examples:

if ($("#elementid").length != 0) {
	//element with this id exists
}

if ($("[name=elementname]").length != 0) {
	//an element with this name exists
}

if ($("#elementclassname").length != 0) {
	//an element with this class name exists
}

Your comments are valued to us, so please feel free to leave some below.


Comments: Your comments will only appear to you until I approve them, only the name, url and comment is shown on this site so make sure you provide a real email address and other details accordingly.
If you would prefer I did not make your comment visible, then please put "IN CONFIDENCE".

Leave a Comment


*


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>