childNodeByID function for Web Extensibility
During the Web Extensibility talk at HP Software Universe, somebody asked me to post the code for childNodeByID. This is a javascript function that is useful in Web Extensibility projects. It lets you find the child of a DOM object that has a specific id attribute.
At the time, I said this function was only a few lines long. I was wrong. Somebody with more javascript experience could probably golf this down to a few lines, but my version is pretty long.
View as plain text
JavaScript:
-
/// <summary>
-
/// Find a DOM element's child node that matches a given string.
-
/// </summary>
-
/// <param name="currentElement" type="HTMLHtmlElement">DOM Element to traverse</param>
-
/// <param name="sID" type="String">html id we're looking for</param>
-
/// <returns type="HTMLHtmlElement">The matching html element</returns>
-
function childNodeByID(currentElement, sID)
-
{
-
if (currentElement)
-
{
-
var result = null;
-
if (currentElement.id == sID)
-
{
-
result = currentElement;
-
}
-
else
-
{
-
// Traverse the tree
-
var i=0;
-
var currentElementChild=currentElement.childNodes[i];
-
while (currentElementChild)
-
{
-
// Recursively traverse the tree structure of the child node
-
result = childNodeByID(currentElementChild, sID);
-
if (result) break;
-
i++;
-
currentElementChild=currentElement.childNodes[i];
-
}
-
}
-
return result;
-
}
-
}
I found the meat of this function at permadi.com and modified it for my own use.
