Sunday, February 11, 2007

Extracting all the elements as veraibles ( javascript extract )

hi,
i wrote a code recently that extracts all the id's of the objects as a variables.
ones
you run this function on body->onLoad it gets all the elements and
defines them by giving them their ids as variable names. function acts
like:



var textbox = document.getElementById("textbox");


for all the elements, it gives you the opportunity of using all of them without even defining.
this function has an equal in PHP(a bit different but it's about the same)
anyway here is the code:


function extract(){
var ie =(document.all)? "var " : "";
var allelems = document.body;
for(var x=0;x < allelems.childNodes.length;x++){
if(allelems.childNodes[x].id){
eval(ie + allelems.childNodes[x].id + " = document.getElementById('"+ allelems.childNodes[x].id +"');");
}
}
}


This
function has some problems first one is, it's not a good thing to run
any unnecessary functions at the onload event. it can cause slowing
down.
Secondly it can cause some problems if you give your elements
the allocated names such as, "for","while","if","document" or "window"
as an ID.
In fact this problem can be solved by modifying the code to make it act like
not define the variables as

var textbox = document.getElementById("textbox");
but define them as

var elems = new Array();
elems["textbox"] = document.getElementById("textbox");
elems["textbox2"] = document.getElementById("textbox2");

this
will solve the problem. if you use the function like this you will have
an associative array that contains all the elements.

I know, it's not "so" useful but in some specific situations it might be really useful like downsizing the file size.
any way, i hope it will be useful, see you later.