Suppose I have an element called "#container-main". How do I make that display:none NOT using jQuery?
6 Answers
document.getElementById('container-main').style.display = 'none';
2 Comments
window.onload handler.getElementById (note case).Although the other answers are correct, for the sake of preventing a potential error, I would recommend getting a reference to your DOM element first, then making sure it exists and has properties, rather than encapsulating everything in a one liner. If, for some reason, the element with id 'container-main' no longer existed on the page, the suggested one-liner will create a JS error.
var myNode = document.getElementById('container-main'); // Attempt to get the reference first
if ( myNode && myNode.style ) { // make sure you did get an element, and if so...
myNode.style.display = 'none'; // then operate on it's properties.
}
Additionally, many people have the erroneous notion that each successive property alteration on the node requires another call to getElementById... this is not the case, and requires additional DOM traversal (which can become slow).
document.getElementById('container-main').style.display = 'none';
document.getElementById('container-main').style.color = 'black'; // getting by id a second time can be slow
-
var myNode = document.getElementById('container-main');
if ( myNode && myNode.style ) {
myNode.style.display = 'none';
myNode.style.color = 'black'; // but using a reference a second time costs nothing.
}
1 Comment
You could also use
document.getElementById('container-main').style.visibility = "hidden";
2 Comments
display: none, and the effect really is quite different.edited:
document.getElementById('container-main').style.display = 'none';
1 Comment
display field on the DOM object itself? The answers above seem to agree that display is part of the style property.