document.exists





-2
Date Submitted Sun. Nov. 12th, 2006 2:08 AM
Revision 1 of 1
Scripter shachi
Tags Document | exists
Comments 0 comments
Checks whether a node exists or not. Not sure about cross browser compatibility though.

function exists_in_dom(satt, sval){
switch(satt){
case "id":
if(document.getElementById(sval)){
return 1;
} else {
return 0;
}
break;
case "class":
var arr = new Array();
var elems = document.getElementsByTagName("*");
for(var attbr, i = 0;(elem = elems[i]);i++){
if(elem.getAttribute("class") == sval){
arr[arr.length] = elem;
}
}
if(arr.length > 0){
return 1;
} else {
return 0;
}
break;
case "name":
namearr = document.getElementsByName(sval);
if(namearr.length > 0){
return 1;
} else {
return 0;
}
break;
}
}


Document.prototype.exists = function(satt, sval){
return exists_in_dom(satt, sval);
}
 

document.exists("id", "somestrangeid"); // returns 1 if it exists, 0 if it doesn't
document.exists("class", "someclass"); // returns 1 if it exists, 0 if not.
document.exists("name", "somestrangename"); // returns 1 if it exists, 0 if it doesn't
 

Shachi Bista

Comments

There are currently no comments for this snippet.

Voting

Votes Up


Syntax Master dannyboy