Introduction

I was working on a fun Chrome extension recently that adds some additional functionality to a web app that I use all the time. Because I don't own this website or have any control over it, I was limited to what I was able to do.

Part of what I wanted to do was add an input above a list of items so that I could add some search like functionality to filter the list. The list can get pretty long so scanning it to find what you're looking for can be cumbersome. In order to do this I needed to be able to get the element that wrapped the list with JavaScript so that I could prepend the input to it.

The problem is that this website was built with React, and the list is it's own component that gets loaded separately from the rest of the page. So I couldn't just write some JavaScript that ran when the page loaded because the list may not exist when it ran. So I needed to write some JavaScript that only ran after the list had loaded.

To do this I created a simple interval that ran a function every 100 ms. All this function did was look for the list, and when it found the list it ran another function and cleared the interval so it wouldn't run continuously.

The Code

waitForElement.js

// set how often you want the condition to be checked
const ms = 100;

// create the interval that runs the function
const timer = setInterval(waitForElement, ms);

// function that will get run
function waitForElement() {
  // check if the element we're looking for exists
  const elementIsLoaded = document.querySelector('.element');

  // if the element exists we can run some code and clear the interval so the function stops running
  if (elementIsLoaded) {
    console.log('the element exists!');
    coolFunctionToRunOnceElementIsLoaded();

    clearInterval(timer);
    return;
  }

  // this will only run if the condition has yet to be met
  console.log('the element does not exist yet...');
}

function coolFunctionToRunOnceElementIsLoaded() {
  alert('Hello, world.');
}