Internet Explorer and Edge browsers present a unique challenge for developers utilizing the forEach() method on the querySelectorAll result. While the method is well-supported in most other browsers, IE and Edge encounter difficulties due to the DOM methods and collection properties employed.
Unlike array-like NodeList instances, which represent a static snapshot of matching elements, HTMLCollection instances are live collections whose changes are reflected in real-time. The forEach() method was only recently implemented in NodeList, while HTMLCollection does not support it. However, both collections are iterable, enabling them to be expanded into arrays or iterated over using the for-of loop or the Symbol.iterator property.
To address the absence of forEach() in NodeList, a simple polyfill can be implemented:
if (typeof NodeList !== "undefined" && NodeList.prototype && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; }
Similarly, if a browser lacks the Symbol.iterator property on NodeList or HTMLCollection, it can be polyfilled as well:
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 }); }
By understanding the differences between NodeList and HTMLCollection, and leveraging the power of polyfills, developers can ensure that the forEach() method operates seamlessly across all browsers, including Internet Explorer and Edge. The code samples provided enable developers to easily implement these polyfills and restore the expected behavior of forEach() in Microsoft browsers.
The above is the detailed content of Why is forEach on querySelectorAll Not Behaving as Expected in Microsoft Browsers?. For more information, please follow other related articles on the PHP Chinese website!