user1941537
user1941537

Reputation: 6675

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?

Upvotes: 1

Views: 37

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

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.

Upvotes: 2

Related Questions