Tyler Churchill | Full Stack Developer
Waiting for DOM Element Existence
01.03.20201 Min Read — In Tutorials

Recently I had the need to do some extra work once an element existed in the DOM. The element I needed to wait for was not in my control and was loaded externally, so I came up with this helper function that can wait for an element to exist in the DOM without blocking the main thread.

const waitForElement = id =>
    new Promise(resolve => {
        const wait = () => {
            const element = document.getElementById(id)
            if (element) {
                resolve(element)
            }
            window.requestAnimationFrame(wait)
        }
        wait()
    })

On a high level, this function takes in an element id (<h1 id="test"></h1> for example), and then waits for the element to be present in the document. You can further adapt this function to search by class or any other attributes for your use case. You could also choose to rework the function to make use of setInterval instead of requestAnimationFrame. I chose requestAnimationFrame as I opted not to worry about cleanup.

Happy coding!

2021
Last build: 14.09.2021