2

I want to convert my code from es6 to es4-3 so that it supports IE11. I am trying to toggle the class="open" for the three button which helps me to open a small div.

JS:

let customSelect = document.getElementsByClassName('input-select')

Array.from(customSelect).forEach((element, index) => {
  element.addEventListener('click', function () {
    Array.from(customSelect).forEach((element, index2) => {
      if (index2 !== index) {
        element.classList.remove('open')
      }
    })
    this.classList.add('open')
  })

  for (const option of document.querySelectorAll('.select-option')) {
    option.addEventListener('click', function () {
      if (!this.classList.contains('selected')) {
        this.parentNode
          .querySelector('.select-option.selected')
          .classList.remove('selected')
        this.classList.add('selected')
        this.closest('.input-select').querySelector(
          '.input-select__trigger span'
        ).textContent = this.textContent
      }
    })
  }

  // click away listener for Select
  document.addEventListener('click', function (e) {
    var isClickInside = element.contains(e.target);
    if(!isClickInside) {
      element.classList.remove('open');
    } 
    return
  })
}) 

HTML:

    <div class="input-select">
     <button></button>
     <div class="select-options">
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div>
<div class="input-select">
     <button></button>
     <div class="select-options">
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div><div class="input-select">
     <button></button>
     <div class="select-options">
       <h1>Hi</h1>
       <h1>Bye</h1>
     </div>
    </div>

This is pure es6 code i need to convert it into lower version of js

7
  • 2
    1. don't use => 2. don't use element.closest 3. don't use element.contains 4. don't use const in for...in for...of
    – Bravo
    Commented Mar 8, 2022 at 8:29
  • 1
    use babel
    – ikhvjs
    Commented Mar 8, 2022 at 8:29
  • 1
    Babel can even be used online -> babel compiler
    – Reyno
    Commented Mar 8, 2022 at 8:30
  • 2
    IE11 fully supports ES5, though.
    – Teemu
    Commented Mar 8, 2022 at 8:30
  • 1
    Additionally to Bravo's list: don't use Array.from and for..of.
    – Teemu
    Commented Mar 8, 2022 at 8:33

2 Answers 2

0

This is the Babel's (targeted only to IE 11) answer:

"use strict";

function _createForOfIteratorHelper(o, allowArrayLike) {
  var it =
    (typeof Symbol !== "undefined" && o[Symbol.iterator]) || o["@@iterator"];
  if (!it) {
    if (
      Array.isArray(o) ||
      (it = _unsupportedIterableToArray(o)) ||
      (allowArrayLike && o && typeof o.length === "number")
    ) {
      if (it) o = it;
      var i = 0;
      var F = function F() {};
      return {
        s: F,
        n: function n() {
          if (i >= o.length) return { done: true };
          return { done: false, value: o[i++] };
        },
        e: function e(_e) {
          throw _e;
        },
        f: F
      };
    }
    throw new TypeError(
      "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
    );
  }
  var normalCompletion = true,
    didErr = false,
    err;
  return {
    s: function s() {
      it = it.call(o);
    },
    n: function n() {
      var step = it.next();
      normalCompletion = step.done;
      return step;
    },
    e: function e(_e2) {
      didErr = true;
      err = _e2;
    },
    f: function f() {
      try {
        if (!normalCompletion && it.return != null) it.return();
      } finally {
        if (didErr) throw err;
      }
    }
  };
}

function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === "Object" && o.constructor) n = o.constructor.name;
  if (n === "Map" || n === "Set") return Array.from(o);
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
    return _arrayLikeToArray(o, minLen);
}

function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) {
    arr2[i] = arr[i];
  }
  return arr2;
}

var customSelect = document.getElementsByClassName("input-select");
Array.from(customSelect).forEach(function (element, index) {
  element.addEventListener("click", function () {
    Array.from(customSelect).forEach(function (element, index2) {
      if (index2 !== index) {
        element.classList.remove("open");
      }
    });
    this.classList.add("open");
  });

  var _iterator = _createForOfIteratorHelper(
      document.querySelectorAll(".select-option")
    ),
    _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done; ) {
      var option = _step.value;
      option.addEventListener("click", function () {
        if (!this.classList.contains("selected")) {
          this.parentNode
            .querySelector(".select-option.selected")
            .classList.remove("selected");
          this.classList.add("selected");
          this.closest(".input-select").querySelector(
            ".input-select__trigger span"
          ).textContent = this.textContent;
        }
      });
    } // click away listener for Select
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  document.addEventListener("click", function (e) {
    var isClickInside = element.contains(e.target);

    if (!isClickInside) {
      element.classList.remove("open");
    }

    return;
  });
});
0

You can use Babel to transpile the code first. You can also refer to this tutorial about how to use Babel to transpile code.

The code I use Babel to transpile is like below:

'use strict';

var customSelect = document.getElementsByClassName('input-select');

Array.from(customSelect).forEach(function (element, index) {
  element.addEventListener('click', function () {
    Array.from(customSelect).forEach(function (element, index2) {
      if (index2 !== index) {
        element.classList.remove('open');
      }
    });
    this.classList.add('open');
  });

  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = document.querySelectorAll('.select-option')[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var option = _step.value;

      option.addEventListener('click', function () {
        if (!this.classList.contains('selected')) {
          this.parentNode.querySelector('.select-option.selected').classList.remove('selected');
          this.classList.add('selected');
          this.closest('.input-select').querySelector('.input-select__trigger span').textContent = this.textContent;
        }
      });
    }

    // click away listener for Select
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  document.addEventListener('click', function (e) {
    var isClickInside = element.contains(e.target);
    if (!isClickInside) {
      element.classList.remove('open');
    }
    return;
  });
});

Then add this line of code before the script to add a polyfill:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js"></script>

Not the answer you're looking for? Browse other questions tagged or ask your own question.