...

element.getElementById instead of document.getElementById

wac
05-13-2004, 05:55 PM
I want to restrict getElementById to search children of a specific element instead of searching the entire document, in the same way that I can do getElementsByTagName using a specific element as the parent.

In this particular instance the parent is a table and the elements I'm interested in are all TDs, so I did the basic getElementsByTagName('TD') off the table and looped through this array checking the IDs. However, I'm suspecting that the browser can do getElementById faster than I can do a loop in javascript. Is there a neater way to do this? For now, I'll settle for IE-only solutions, though it would be nice to have things work in generic browsers.

liorean
05-13-2004, 06:02 PM
Well, have a look at this post

wac
05-13-2004, 06:57 PM
Yes,
That's the basic gist of things. I was hoping that there was some way to do it without the javascript loop. I know how to write such a function, but I thought if there was a way for the browser to do it, this would surely be faster than a javascript loop.

Here's another thing. I guess this should be a separate post.
Suppose I have an associative array (an array with string index instead of numeric index) would that access be faster than looping through an integer indexed array. Here's my thought process....

I create an associative array using the element ID as the index and the appropriate value (the element object), then each subsequent access would be
myelem = myarray[id] ;
where id is the string id of the element I want.

liorean
05-13-2004, 07:28 PM
The browser has no built-in function for doing this. The one I posted there:var
oDiv=document.getElementById('elementId');

function isDecendant(decendant,ancestor){
return ((decendant.parentNode==ancestor) ||
(decendant.parentNode!=document) &&
isDecendant(decendant.parentNode,ancestor));
}

if(oDiv && isDecendant(oDiv, oAncestor)){
/* do something with oDiv */
}...is probably the fastest way of getting an element with a certain id only under the circumstances that it is a decendant of a certain other element. It will be in most cases be faster than iterating through the decendants of that element.

Renato Bebić
09-02-2009, 09:31 PM
I needed this functionality so i written this:


/**
* Function will get element by id starting from specified node.
* Author: Renato Bebić <renato.bebic@gmail.com>
*
*/
function GetElementById( dNode, id ) {

var dResult = null;

if ( dNode.getAttribute('id') == id )
return dNode;

for ( var i = 0; i < dNode.childNodes.length; i++ ) {
if ( dNode.childNodes[i].nodeType == 1 ) {
dResult = GetElementById( dNode.childNodes[i], id );
if ( dResult != null )
break;
}
}

return dResult;
}


I tried to make HTMLElement.prototype.getElementById but IE does not support prototyping on HTMLElement.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum