模拟 IE7 的 getElementById 行为

问题描述 投票:0回答:1

背景

我有一个当前在 Edge Internet Explorer 模式下运行的 Web 应用程序。我想将此应用程序移植到 Edge 或 Chrome 等现代浏览器。

此应用程序中的 JavaScript 依赖于 IE7 文档模式 (https://learn.microsoft.com/en-us/internet-explorer/ie11-deploy-guide/img-ie11-docmode-lg)。例如,此应用程序大量使用

getElementById()
,并假设
getElementById()
对 ID 和 NAME 属性执行不区分大小写 匹配。

问题

当然,您可以根据现代 JavaScript API 中的

getElementById()

 规范重写此应用程序。但这个应用程序有如此多的 JavaScript 文件,因此需要大量的非显而易见的工作。所以我正在寻找一些解决方法。

问题

有没有办法在现代浏览器上模拟 IE7 文档模式

getElementById()

 的行为?

例如,如何反向填充

getElementById()

的行为来模仿它在IE7上的行为?

javascript internet-explorer polyfills
1个回答
0
投票
获取所有

可能具有您想要的名称或ID的元素的列表,然后过滤它们以找到第一个匹配的元素。

const getElementCaseInsensitivelyByNameOrId = (nameOrId) => { // Start by getting a list of prospective elements. // You could also use querySelectorAll("[id], [name]") for efficiency but that might skip elements where the ID or name is set as a property (not an attribute) with JS const prospectiveElements = document.querySelectorAll("*"); // Convert to an array for access to the methods on array.prototype const arrayProspectiveElements = [...prospectiveElements]; // Lower case the search term const searchTerm = nameOrId.toLowerCase(); // Perform the search const firstMatch = arrayProspectiveElements.find(element => element.id?.toLowerCase() === searchTerm || element.name?.toLowerCase() === searchTerm); return firstMatch; }; const foo = getElementCaseInsensitivelyByNameOrId("FOO"); const bar = getElementCaseInsensitivelyByNameOrId("BAR"); const sirNotAppearingInThisDocument = getElementCaseInsensitivelyByNameOrId("sirNotAppearingInThisDocument"); console.log({ foo, bar, sirNotAppearingInThisDocument });
<div id="Foo">Foo</div>
<input name="bAR" value="bAR">

或者更简洁地说:

const getElementCaseInsensitivelyByNameOrId = (nameOrId) => { const t = nameOrId.toLowerCase(); return [document.querySelectorAll("*")].find(e => e.id?.toLowerCase() === t || e.name?.toLowerCase() === t); }
    
© www.soinside.com 2019 - 2024. All rights reserved.