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

Billboard image

The fastest way to detect downtimes

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitoring.

Get started now

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay