tags:

views:

110

answers:

5

Suppose I have an element called "#container-main". How do I make that display:none NOT using jQuery?

+9  A: 
document.getElementById('container-main').style.display = 'none';
cobbal
And you need to do this after the element is rendered. Either by placing your script after the element, or using a `window.onload` handler.
Ates Goral
Should be `getElementById` (note case).
tloflin
@tloflin thanks, fixed
cobbal
+10  A: 

I'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';
Miguel Ventura
A: 

edited: document.getElementById('container-main').style.display = 'none';

vittore
Is there really a `display` field on the DOM object itself? The answers above seem to agree that `display` is part of the `style` property.
Jørn Schou-Rode
yep you're right
vittore
A: 

You could also use

document.getElementById('container-main').style.visibility = "hidden";
born to hula
You could, but that would not set `display: none`, and the effect really is quite different.
Jørn Schou-Rode
@Jorn: my bad. but what would be the difference between the two approaches?
born to hula
+3  A: 

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.
}
Slobaum
Agreed, this was the comment I was going to make. Check that the element was retrieved successfully before trying to set the style property.
Alex JL