jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
There are three methods how to implement 'getElemsByClassName'. One is getting all elements by specifying an asterisk in the argument of getElemsByTagName. Two is recursively searching nodeList from childNodes. The other is using XPath but limitted browsers are supporting one. (However, the former method is not able to specify a parent element but I think it is not be a problem so much in the case of getting class name.)
<div class="parent">
<div class="child a">a.text</div>
<div class="child b">b.text</div>
</div>
// Case of using getElementsByTagName
function getElementsByClassName_A(className) {
var elements = [];
var haystacks = document.getElementsByTagName('*');
for (var i = 0; i < haystacks.length; ++i)
if (hasClassName(haystacks[i], className)) elements.push(haystacks[i]);
function hasClassName(element, className) {
var classes = element.className.split(' ');
for (var i = 0; i < classes.length; ++i)
if (classes[i] === className) return true;
return false;
}
return elements;
}
// Case of recursively searching nodeList
function getElementsByClassName_B(element, className) {
var elements = [];
(function(element) {
var childNodes;
if (element.nodeType === 1 && hasClassName(element, className))
elements.push(element);
if ((childNodes = element.childNodes) !== null)
for (var i = 0; i < childNodes.length; ++i) arguments.callee(childNodes[i]);
})(element);
function hasClassName(element, className) {
var classes = element.className.split(' ');
for (var i = 0; i < classes.length; ++i)
if (classes[i] === className) return true;
return false;
}
return elements;
}
// Case of using XPath
function getElementsByClassName_C(element, className) {
var elements = [];
var xpath = document.evaluate(
'.//*[contains(concat(" ", @class, " "), "' + className + '")]',
element, null, XPathResult.ANY_TYPE, null
);
for (var item = xpath.iterateNext(); item; item = xpath.iterateNext())
elements.push(item);
return elements;
}
Ready to run.
Test | Ops/sec | |
---|---|---|
Case of using getElementsByTagName |
| ready |
Case of recursively searching nodeList |
| ready |
Case of using XPath |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.