For all browsers, you can use Array.prototype.slice
via call
or apply
(it works on any array-like object):
Array.prototype.slice.call(document.querySelectorAll('.row'))
About your updated question:
Im using this for 'click' event handling:
Array.prototype.slice.call(document.querySelectorAll('.row'))
.forEach(function(header) {
return header.addEventListener('click', function(e) {
headerClick(e, header, header.querySelector('.exy'))
});
});
I wouldn't use querySelectorAll
for this at all, I'd use event delegation. Presumably all of those .row
elements are inside a common container (ultimately, of course, they're all in body
, but hopefully there's a container "closer" to them than that). With event delegation, you do this:
Hook click
just once, on the container
When a click occurs, check to see if it passed through one of your target elements en route to the container
For your quoted code, that looks something like this:
// A regex we'll reuse
var rexIsRow = /row/;
// Hook click on the container
document.querySelector("selector-for-the-container").addEventListener(
"click",
function(e) {
// See if we find a .row element in the path from target to container
var elm;
for (elm = e.target; elm !== this; elm = elm.parentNode) {
if (rexIsRow.test(elm.className)) {
// Yes we did, call `headerClick`
headerClick(e, elm, elm.querySelector('.exy'));
// And stop looking
break;
}
}
},
false
);
On more modern browsers, you could use elm.classList.contains("row")
instead of the regular expression, but sadly not on IE9 or earlier.
That said, rather than maintaining a separate codebase, as gcampbell pointed out you could use ES6 (ES2015) features in your code and then transpile with a transpiler that converts them (well, the ones that can be converted, which is a lot of them) to ES5 syntax. Babel is one such transpiler.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…