getElementsByTagName()

It turns out that document fragments do not implement the getElementsByTagName() method. But they do implement the Selectors API methods: querySelector/querySelectorAll .

Nobody cares about this except for people that write JavaScript selector engines. If you are one of those people then keep reading.

I can code around the absence of a lot of DOM methods but getElementsByTagName() seemed impossible to do without. So I had to fake it!

JavaScript performance

JavaScript is a nice enough scripting language but it is still a scripting language.

For high performance loops you should try to avoid the following:

try / catch blocks function/method calls (even on native objects) accessing DOM properties (or anything that involves calling a complex getter/setter)

Please note that this is an ordered list.

The code

With all that in mind I wrote this simple implementation of getElementsByTagName() which I hope is fast enough for those edge cases where users execute DOM queries on document fragments:

function getElementsByTagName(node, tagName) { var elements = [], i = 0, anyTag = tagName === "*", next = node.firstChild; while ((node = next)) { if (anyTag ? node.nodeType === 1 : node.nodeName === tagName) elements[i++] = node; next = node.firstChild || node.nextSibling; while (!next && (node = node.parentNode)) next = node.nextSibling; } return elements; }