Binary Journey

[Javascript][IE] Internet Explorer getElementsByName, querySelectorAll ForEach 지원하지 않는 문제: Array.from 사용 본문

Issue

[Javascript][IE] Internet Explorer getElementsByName, querySelectorAll ForEach 지원하지 않는 문제: Array.from 사용

binaryJournalist 2022. 4. 14. 10:30
반응형

 

 

document.querySelectorAll
document.getElementsByName

 

 

으로 개체를 가져오면 크롬이나 다른 웹브라우저에서는 NodeList 의 forEach를 지원해주는데

Internet Explorer 는 지원해주지 않아서 안된다.

 

찾아보면 ie9 이상이면 된다고 하지만 나는 ie11을 사용하는데도 안됨^^

 

 

https://stackoverflow.com/questions/46929157/foreach-on-queryselectorall-not-working-in-recent-microsoft-browsers

 

forEach on querySelectorAll not working in recent Microsoft browsers

I am making a script for choices about a product (colors etc), which works in every browser except for Internet Explorer (11) & Edge. I put the choices of each parameter in a array and apply a

stackoverflow.com

 

 

 

 

 

대한민국 웹브라우저 중 ie 점유율이 2021년 12월 기준 1.43%라고 하던데

 

 

 

여튼

 

 

document.querySelectorAll 를 사용하는 경우

return 값 전체를 Array.from() 으로 감싸주면 된다.

 

Array.from(document.querySelectorAll("li[name='li이름']"))

 

아니면 destructuring을 해도 된다.

 

const li이름 = document.querySelectorAll("li[name='li이름']");
const allLi = [...li이름];

 

document.getElementsByName 는 Array.from()으로 감싸도 ie 에서 안 된다

 

그래서 querySelectorAll를 대신 사용해야 한다.

 

 

다른 방법으로는 NodeList의 forEach를 정의해주면 된다.

 

if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) {
    // Yes, there's really no need for `Object.defineProperty` here
    NodeList.prototype.forEach = Array.prototype.forEach;
}

if (typeof Symbol !== "undefined" && Symbol.iterator && typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype[Symbol.iterator]) {
    Object.defineProperty(NodeList.prototype, Symbol.iterator, {
        value: Array.prototype[Symbol.iterator],
        writable: true,
        configurable: true
    });
}
반응형