0

A couple of days ago, I've asked how to shorten my codes. Shortly after, I've gotten an answer, and it was terrific. However, I've found out that it's not working in ... guess what... (IE).

This was the codes:

for (var i = 0; i < 1; i++) {
    var title = document.querySelector("h1.title"),
        date = document.querySelector(".article-date"),
        tme = document.querySelector(".article-tme"),
        src = document.querySelector(".source"),
        user = document.querySelector(".user"),
        tip = document.querySelector(".tip");
        //.....some other variables...

    title.innerHTML = post[i].titles;
    date.innerHTML = post[i].dates;
    src.innerHTML = post[i].sources;
    tme.innerHTML = post[i].times;
    user.innerHTML = post[i].authors;
    tip.innerHTML = post[i].excerpts;
    //....some other HTML content setting...
}

And this was the answer:

const selectorsByProp = {
  titles: 'h1.title',
  dates: '.article-date',
  sources: '.source',
  // ...
}
Object.entries(selectorsByProp).forEach(([prop, selector]) => {
  document.querySelector(selector).innerHTML = post[i][prop];
});

Unfortunately, this is not the case in IE. Instead, it shows a blank page. I've already enforced it with polyfill for Object.entries and Object.key but it still giving me an error. Thank you.

DaOneRom
  • 284
  • 4
  • 18
  • Are you using Babel? – CertainPerformance Sep 07 '19 at 09:58
  • No version of IE supports arrow functions or destructuring. If you're polyfilling `Object.entries`, you can just use a traditional function in your code instead (and remove the destructuring), since it doesn't need the features of the arrow function: `Object.entries(selectorsByProp).forEach(function(entry) { var selector = entry[0]; var prop = entry[1]; document.querySelector(selector).innerHTML = post[i][prop]; }); ` Or, of course, use a modern JavaScript to old JavaScript compiler/transpiler like [Babel](https://babeljs.io/). – T.J. Crowder Sep 07 '19 at 10:03
  • 1
    If you're *not* polyfilling `Object.entries` you can use a `for-in` loop, which is arguably simpler anyway: `var prop; for (prop in selectorsByProp) { document.querySelector(selectorsByProp[prop]).innerHTML = post[i][prop]; });` – T.J. Crowder Sep 07 '19 at 10:07
  • 1
    Side note: Beware of `const` and `let` in IE11. Although they *mostly* work correctly, `let` in particular does not behave correctly when declared within a `for` loop, because IE11's version predates the ES2015 specification and implemented an incomplete version. – T.J. Crowder Sep 07 '19 at 10:08
  • @CertainPerformance. No, I'm not using Babel. Though I'm using Laravel, and since it has a built-in babel when I install npm, I can't use it because I'm still not familiar with it. – DaOneRom Sep 07 '19 at 10:22

0 Answers0