Skip to content

Instantly share code, notes, and snippets.

@atk atk/LICENSE.txt forked from 140bytes/LICENSE.txt
Last active Dec 18, 2015

Embed
What would you like to do?
getElementsByClassName Shim

getElementsByClassName Shim

This is the slimmest replacement for getElementsByClassName I could think of. Only drawback is that it doesn't work for document, only with document.body. If you replace "children" with "childNodes", it will also support document.

function C(
c, // className
n, // nodeList
r, // result
i // index
){
// initialize result array
r = r || [];
// walk nodeList or an array containing "this" (node from which it is called)
for (i in n=n || !i && [this])
// recursively iterate over children (use .childNodes for document, alas
// this breaks the 140bytes barrier)
C(c,(i=n[i]).children,r,1),
// create RegExp through eval to test for className, add to result if present
eval('/\\b' + c + '\\b/').test(i.className) && r.push(i);
// return result
return r
}
function C(c,n,r,i){r=r||[];for(i in n=n||!i&&[this])i=n[i],C(c,i.childNodes,r,1),eval('/\\b'+c+'\\b/').test(i.className)&&r.push(i);return r}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Alex Kloss <alexthkloss@web.de>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": ".getElementsByClassName shim",
"description": "Replacement for the node.getElementsByClassName method for older clients",
"keywords": [
"DOM",
"nodes"
"className",
"shim"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div class="any test">Expected value: <b>2</b> (2 divs having the className "test"</div>
<div class="test and more">Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
function C(c,n,r,i){r=r||[];for(i in n=n||!i&&[this])i=n[i],C(c,i.childNodes,r,1),eval('/\\b'+c+'\\b/').test(i.className)&&r.push(i);return r}
document.getElementById( "ret" ).innerHTML = C.call(document.body, 'test').length;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.