Reputation: 442
I have tried out a custom getElementById() method to retrieve DOM element from a HTML page. This is the definition.
document.customGetElById = function(passedId){
var nodeFound = null;
recursive = function(nodes)
{
for(var i =0 ; i< nodes.length; i++)
{
if(nodes[i].nodeType == 1) //element nodes
{
//console.log(nodes[i].id); //only element nodes have id's
if(nodes[i].id == passedId)
{
//console.log(nodes[i]);
nodeFound = nodes[i];
return;
}
if(nodes[i].childNodes)
{
//console.log('there are child nodes inside it');
recursive(nodes[i].childNodes);
}
}
}
}
recursive(document.body.childNodes);
return nodeFound;
};
Is this a correct way of doing it? Is this good for performance? It has nothing to do to override the native getElementById() method. How is the native function written? Can somebody help me out? Thanks in advance.
Upvotes: 1
Views: 1090
Reputation:
Native functions are not written in JS, so any JS approach will necessarily differ from the original getElementById
.
Your function will also probably be less efficient than the browser's implementation, since all you are doing is reproducing it from a plethora of other native functions.
Upvotes: 2