Extelliqent
Extelliqent

Reputation: 1856

Javascript if/else question

I wanna open a div and close it with this function but it doesnt work where is the wrong part i couldnt fix it, can anyone help me ?

function Element(id)
{    
    if(document.getElementById(id).style.display = 'block')
    {
        document.getElementById(id).style.display = 'block';
    }
    else
    {
        document.getElementById(id).style.display = 'none';
    }
}

Upvotes: 0

Views: 2876

Answers (5)

m0sa
m0sa

Reputation: 10940

I would suggest you rewrite it with the ternary operator, its much more readable and maintainable:

var element = document.getElementById(id);
element.style.display = element.style.display === 'block' ? 'none' : 'block';

Upvotes: 3

El Ronnoco
El Ronnoco

Reputation: 11912

You don't need an else or a ternary operator as your first condition has no effect. So this will suffice...

if(document.getElementById(id).style.display != 'block')
{
    document.getElementById(id).style.display = 'none';
};

Upvotes: 0

Extelliqent
Extelliqent

Reputation: 1856

Thank you ! This one worked.! but I changed the code inside of if. Because it says if you find block which should be none.

function Element(id) { 
    if( document.getElementById(id).style.display == 'none') {
      document.getElementById(id).style.display = 'block';
    } else { 
      document.getElementById(id).style.display = 'none'; 
    } 
}

Upvotes: 1

Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9973

function Element(id) { 
        if( document.getElementById(id).style.display == 'block') {
             document.getElementById(id).style.display = 'block';
       } else { document.getElementById(id).style.display = 'none'; }
} 

Upvotes: 1

SLaks
SLaks

Reputation: 888107

Your if statement assigns the property instead of comparing it.
Change = to ===.

Upvotes: 3

Related Questions