• 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 run a callback function when it does. It seems simple enough, but what’s the easiest way?

By using an async function and a while loop, we can wrap setTimeout in a promise, then await it, and then resolve the promise when the timeout completes. As you can see, it will continue the loop until we reach the timeout passed into the function (or the element is found).

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

  while (Date.now() - start < timeout) {
    const el = document.querySelector(selector);
    if (el) {
      return el;
    }
    await new Promise(resolve => setTimeout(resolve, 1000));
  }

  return null;
}

There are lots of other ways you can achieve this concept, from using setInterval to using a MutationObserver, but this approach is cleaner and easier to understand.

Dwayne

Leave a Reply Cancel reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
BBosman
BBosman
4 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”.

3

Primary Sidebar

Popular

  • I Joined Truth Social Using a VPN and Editing Some HTML to Bypass the Phone Verification
  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Thoughts on the Flipper Zero
  • Waiting for an Element to Exist With JavaScript
  • How To Paginate An Array In Javascript
  • How To Mock uuid In Jest
  • How To Decompile And Compile Android APK's On A Mac Using Apktool
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • Wild Natural Deodorant Review

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz