Skip to content

Instantly share code, notes, and snippets.

@cayasso
Created January 22, 2012 08:44
Show Gist options
  • Save cayasso/1656290 to your computer and use it in GitHub Desktop.
Save cayasso/1656290 to your computer and use it in GitHub Desktop.
My custom getElementById
<!DOCTYPE html>
<html>
<head>
<title>BFS</title>
</head>
<body>
<div>
<em>
<em>
<h1>This is a title</h1>
<p>Some text there</p>
</em>
</em>
</div>
<div>
<div>
<ul>
<li><a href="#">Item 1<span></span></a></li>
<li><a href="#">Item 2<span></span></a></li>
<li><p><a href="#">Item 3<span></span></a></p></li>
<li>
<p><a id="my-unique-id" href="#">Item 4<span></span></a></p>
</li>
</ul>
</div>
</div>
<script>
/**
* Get an element from the dom by ID using BFS
* @param {String} id The ID you are searching for
* @param {Array} group This is for internal use only
* @return {Object}
*/
function getById(id, group) {
var _group = [];
group = group || [[document]];
for (var j = 0, l = group.length; j < l; j++) {
var nodes = group[j];
for (var i = 0, ln = nodes.length; i < ln; i++) {
var child = nodes[i];
if (child.nodeType !== 1 && child.nodeType !== 9 && child.nodeType !== 9) {
continue;
} else {
if (child.id === id) {
return child;
}
if (child.childNodes) { //console.log('Node name ===> ', child.nodeName);
_group.push(child.childNodes);
}
}
}
}
return (_group.length) ? getById(id, _group) : null;
}
// A better way, its more code but a lot more efficient
// The non-recursive traversal
function getById2 (id, root) {
var child = root || (root = document),
node = null;
do {
node = child.firstChild;
if (node === null) {
node = child.nextSibling;
}
if (node === null) {
var _child = child;
do {
node = _child.parentNode;
if (node === root) {
break;
}
if (node.nodeType !== 1 && node.nodeType !== 9 && node.nodeType !== 9) {
// Skip non html tags like text nodes
} else {
if (node.id === id) {
return node;
}
}
_child = node;
node = node.nextSibling;
}
while (node === null)
}
child = node;
}
while (child !== root);
return null;
}
// use the Firefox Firebug profiling tab in console to see results.
// getById2 is much faster execution time it is 0.264ms vs getById 1.612ms
console.time('getById');
console.log('RESULT TAG IS: ', getById('my-unique-id').nodeName);
console.timeEnd('getById');
console.time('getById2');
console.log('RESULT TAG IS: ', getById2('my-unique-id').nodeName);
console.timeEnd('getById2');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment