• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

Waiting for an Element to Exist With JavaScript

Javascript · October 20, 2022

There are many different ways to solve this use case. You want to wait for an element to exist on the page and when it does, run a callback function. It seems simple enough, but what’s the easiest way?

By using some recursion and a setInterval call, we can poll for an element using document.querySelector and if it exists before the timeout value is reached, we return it by calling the callback function with our element.

function waitForElement(selector, callback, timeout = 15000) {
  const start = Date.now();

  let interval = setInterval(() => {
    const el = document.querySelector(selector);

    if (el) {
      clearInterval(interval);
      callback(el);
    } else if (Date.now() - start > timeout) {
      clearInterval(interval);
      callback(null);
    }
  }, 1000);
}

You can achieve the same thing with a setTimeout, you can even use a MutationObserver to observe the element. In this instance, using an interval works for me.

Dwayne

Leave a Reply Cancel reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
BBosman
BBosman
3 months ago

You could shorten the “if” to:
if (el || Date.now() – start > timeout)

If the “querySelector” can’t find the element it will return “null”, making the “if” and “else if” the same as it’ll call the callback with an “el” of “null”.

1

Primary Sidebar

Popular

  • Thoughts on the Flipper Zero
  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • How To Paginate An Array In Javascript
  • Waiting for an Element to Exist With JavaScript
  • Reliably waiting for network responses in Playwright
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How to Use Neural DSP Archetype Plugins With the Quad Cortex
  • Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • How To Install Eufy Security Cameras Without Drilling or Using Screws

Recent Comments

  • Kevmeister68 on Start-Ups and Companies That Embrace Work From Anywhere Will Be More Likely to Survive the Coming Recession in 2023
  • kevmeister68 on What Would Get People Back Into the Office?
  • Dwayne on PHP Will Not Die
  • Dwayne on How to Create a Blockchain With TypeScript
  • kevmeister68 on PHP Will Not Die

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz