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

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay