Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

241
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda