Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save lacikawiz/04021b654286e582d015b4fd7128122e to your computer and use it in GitHub Desktop.

Select an option

Save lacikawiz/04021b654286e582d015b4fd7128122e to your computer and use it in GitHub Desktop.
Vanilla JS Wait for elements to appear in DOM

Run JS code on DOM elements as soon as they appear

This code is written to handle cases when the DOM is being generated, like Angular, Ractive or Svelte, etc. It does a quick (100ms) repeated check for the existence of the DOM elements and when they appear it runs the given function on each elements.

//Common function, waits for the element to appear in the DOM, and then runs the `func` for each element matched
function waitForElement(selector,func){
var intval=setInterval(function(){
var match=document.querySelectorAll(selector) //checking the selector for existence
if(match.length!=0) {
clearInterval(intval)
match.forEach(func)
}
},100)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment