DEV Community

mixbo
mixbo

Posted on • Edited on

2

write more flexbox code to query document element.

Alt Text

Sometimes you need check if HTML element present in document, special your dom load from remote server and dynamic add to document.

If you code query DOM when document loaded, firt time the DOM maybe present you can queried it.

But if your DOM load from server, you query code clound not found it anymore. becuase you query code execute before **DOM **add to document

How reslove it? show me code to you

const awaitSomethingReady = (condition, maxCount = 500) => {
  return new Promise((resolve, reject) => {
    let getTestIntervalId = null
    const maxCheckCount = maxCount || 500
    let currentCheckCount = 0
    getTestIntervalId = setInterval(() => {
      currentCheckCount += 1
      if (maxCheckCount === currentCheckCount) {
        clearInterval(getTestIntervalId)
        reject()
      }
      if (condition()) {
        clearInterval(getTestIntervalId)
        resolve()
      }
    }, 50)
  })
}
Enter fullscreen mode Exit fullscreen mode

I just want to check if div with calss toolbar present so use awaitSomethingReady

awaitSomethingReady(document.querySelector(".toolbar")).then(()=>{
  console.log("found toolbar")
}).catch(()=>{
  console.log("will found toolbar continue ...")
})
Enter fullscreen mode Exit fullscreen mode

That all you will write more flexible code

another way to quickly use npm live-query

Hope it can help you

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay