Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda