Search code examples
javascriptgoogle-chrome-extensionmanifest

TypeError: element.forEach is not a function


I am wanting to make a Chrome extension that will replace the word 'Corona Virus' with my word of choice. In my script.js I am using a recursive function that checks to see if there are any 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')
    }
}`

In my console I am receiving an error saying Uncaught TypeError: element.hasChildNodes.forEach is not a function and Uncaught TypeError: Cannot read property 'forEach' of undefined. Any reason why this error is happening?


Solution

  • Elements don't have a forEach method. (Neither does the hasChildNodes function that they have.) They aren't arrays or NodeLists.

    On modern browsers, element.childNodes has forEach because it's a NodeList and a couple of years ago they got forEach (and iterability), so:

    element.childNodes.forEach(replaceText);
    

    On older browsers that haven't added that yet, you can use Array.from to get a true array, then use forEach:

    Array.from(element.childNodes).forEach(replaceText);
    

    Or you can polyfill it on NodeList, as I show in this other answer.