Skip to content
Advertisement

if display is block change it to none with javascript

for this code

#element { 
  display : block
}

<div id="element"></div>

how can I write javascript code like

// button on click
if(element-display = block){
    // change it to display = none
}

Advertisement

Answer

try this,

document.querySelector("button").addEventListener("click", changeDiv);
function changeDiv(){
	var element = document.getElementById("element1");
    element.style.display = (element.style.display == 'none') ? 'block' : 'none';
}
#element1{display:block}
<div id="element1">Sample</div>
<button>Click here</button>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement