简体   繁体   中英

How to hide an element by condition in JavaScript?

I'm going to set a parameter for an iframe that sets to 1 or 0. then if the parameter is 1 a div by class="badge" will visible else hide.

How can I define this condition in JavaScript? Thank you for your help :)

This is my HTML and CSS code.

 .badge { font-family: Tahoma; position: absolute; left: 0; bottom: 0; background: #7bbded; color: white; border-radius: 0 0px 0 0; font-size: 10px; padding: 1px 6px 0 3px; } 
 <iframe scrolling="no" style="" src="" frameborder="0"> <div id="main" style="width: 100%; height: 100%;"> <div class="ad-container" id="container"> <a href="#" target="_blank" onclick="cmp_link_clicked()"> <img class="text-icon" alt="آموزش های فرادرس" title="آموزش های فرادرس" src="https://beta.kaprila.com/a/images/video-icon.gif"> <h3 id="title">فیلم‌&nbsp;آموزشی <span class="important">تافل <span class="ltr">(TOEFL)</span></span> تشریح آزمون — <strong>کلیک کنید</strong></h3> <div class="badge" id="badge" style="display: block;"> تبلیغات </div> </a> </div> </div> </iframe> 

First, get a reference to the div:

var div = document.querySelector('.badge');

Then, add a new class, like show :

if(parameter === 1){
 div.classList.add('show');
}

parameter should be the name of your parameter stored in a var.

Besides, you could set display: block in your css file, not as inline style.

Like this:

.badge {
    font-family: Tahoma;
    position: absolute;
    left: 0;
    bottom: 0;
    background: #7bbded;
    color: white;
    border-radius: 0 0px 0 0;
    font-size: 10px;
    padding: 1px 6px 0 3px;
    display:none; // ---> Hidden by default
}

.badge.show {
    display:block; // --> Visible only when you have .badge and .show classes in the same element
}

To remove the class, you can use classList.remove('show');

if(parameter === 0){
    div.classList.remove('show');
}

Check docs here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM