I K I K - 4 months ago 23
Javascript Question

ES6 spread operator IE not supported

I have a javascript code that is given below that is ES6 compatible however IE 11 does not support this. What would be the replacement code for this such that it works across all browsers?

[...document.querySelectorAll('.row')]


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'))
});
});

Answer

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 = /\brow\b/;
// 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.

Comments