我想制作一个Chrome扩展,将 "Corona Virus "一词替换为我选择的词语。在我的 script.js 中,我使用了一个递归函数来检查是否有任何 ChildNodes。`
replaceText(document.body)
function replaceText(element){
if(element.hasChildNodes()){
element.forEach(replaceText);
} else if(element.nodeType === Text.TEXT_NODE) {
element.textContent = element.textContent.replace(/coronavirus/gi,
'Blehh')
}
}`
在我的控制台中,我收到一个错误信息说 Uncaught TypeError: element.hasChildNodes.forEach is not a function
和 Uncaught TypeError: Cannot read property 'forEach' of undefined
. 有什么原因会出现这种错误吗?
元素没有 forEach
方法。(也没有 hasChildNodes
函数)。) 它们不是数组或 NodeList
s.
在现代浏览器上。element.childNodes
有 forEach
因为这是一个 NodeList
几年前,他们得到了 forEach
和可迭代性),所以。
element.childNodes.forEach(replaceText);
在旧的浏览器上,如果还没有添加这个功能,你可以使用... Array.from
得到一个真数组,然后用 forEach
:
Array.from(element.childNodes).forEach(replaceText);
或者你可以把它填上 NodeList
, 正如我在另一个答案中所说.