简体   繁体   中英

if and else statement for id and class to change margin

I have try to fix my javascript / for (if statement) i trying to make if getElementsByid ('box')on href else change style for class ""bg to margin-top:10px

HTML code

<a href="#" id="box">click</a>

<div class="bg">Test</div>

<style>
.bg{
margin-top:100px; 
}
</style>

Script

function Element(id) { 
    if( document.getElementById('box') {
      document.getElementById('box').style.display = 'block';
    } else { 
      document.getElementsByClassName('bg').style.marginTop:'10px'; 
    }  }

document.getElementsByClassName(cname) returns an array so you are not doing the right thing.

try

document.getElementsByClassName('bg')[index].style.marginTop

where index is the number

HTML

<a href="#" id="box">click</a>

<div class="bg">Test</div>

JAVASCRIPT

function element(id, index){
    if( index === null ){
        document.getElementById(id).style.display = 'block';
    }else{
        document.getElementsByClassName(id)[index].style.marginTop = '10px';
    }
}

element('bg', 0);

Fiddle to answer here

Unfortunately I can't comment posts, so I just want to notice to @Hawk 's post. 'bg' is not an ID, it's a class. so I guess the right way is

function element(id, elClass, index){
    if( index === null ){
        document.getElementById(id).style.display = 'block';
    }else{
        document.getElementsByClassName(elClass)[index].style.marginTop = '10px';
    }
}

element('box', 'bg', 0);

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