Created
January 22, 2012 09:00
-
-
Save cayasso/1656324 to your computer and use it in GitHub Desktop.
My Get By ID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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; | |
} | |
console.log('RESULT TAG IS: ', getById('my-unique-id').nodeName); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment