Suppose I have an element called "#container-main". How do I make that display:none NOT using jQuery?
views:
110answers:
5I'm assuming that you mean the id attribute of the container is container-main. Then in JavaScript you do
document.getElementById('container-main').style.display = 'none';
edited:
document.getElementById('container-main').style.display = 'none';
You could also use
document.getElementById('container-main').style.visibility = "hidden";
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.
}