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.


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
 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))
 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!


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
Author: Dean WilliamsI'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
, ,
0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments