Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
How can I merge these tow block of code together to simplify it?

I'm checking two different divs after a setTimeOut of 2 seconds to see if they contain an iFrame or not. If they don't I just set their display to none to hide them. Important is that these two divs never exist together on one page. Now I put the following code together and it's working fine:

let divOne = document.querySelector('.div-one')
if (divOne) {
    setTimeout(() => {
        let divOneIframe = divOne.querySelector("iframe")

        if (!divOneIframe) {
            divOne.style["display"] = "none";
        }
    }, 2000)
}

let divTow = document.querySelector('.div-two')
if (divTow) {
    setTimeout(() => {
        let divTwoIframe = divTow.querySelector("iframe")

        if (!divTwoIframe) {
            divTow.style["display"] = "none";
        }
    }, 2000)
}

But it doesn't seem right to me to have to separate setTimeOut for it.

How can I merged these two block of codes so that I end up with using setTimeOut only once?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Iterating over an array of those possible selectors would work.

const div = ['.div-one', '.div-two']
    .map(sel => document.querySelector(sel))
    .find(Boolean);
if (div) {
    setTimeout(() => {
        const iframe = div.querySelector('iframe');
        if (!iframe) {
            div.style.display = 'none';
        }
    }, 2000);
}

With optional chaining:

Another approach would be to give .div-one and .div-two their own selector in common - eg, have <div class="div-one contains-iframe"> and <div class="div-two contains-iframe"> so that you only have to select .contains-iframe rather than iterate.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!