Hiding an element: Difference between Javascript attribute and CSS style

Jbartmann picture Jbartmann · Dec 11, 2013 · Viewed 49k times · Source

I wonder if there is any difference in the result when hiding an element with JavaScript attribute or CSS Style.

For example:

element.setAttribute("hidden", true);

vs

element.style.visibility = "hidden";

I experimented a bit with those two possibilities. My assumption is, that when hiding it with JavaScript, the element is truly hidden and taken out of the flow; and when hiding with CSS Style the element is just not shown but still there.

Mostly this seemed right in my experiments, but sometimes not. So, what is the real difference between those two possibilities?

Answer

Olly Hodgson picture Olly Hodgson · Dec 11, 2013

There's two basic methods for hiding an element with CSS:

Firstly, there's visibility: hidden; (or element.style.visibility = "hidden";). This simply makes the item invisible. It still takes up space in the document, it's still part of the flow.

Then there's display: none; (or element.style.display = "none";). This removes the element from the flow of the document entirely. It's still present in the DOM, it's just not rendered to the page.

HTML5's hidden attribute (or element.setAttribute("hidden", true);) is roughly equivalent to display: none;.

In fact, to give older browsers compatibility with the attribute, this is often added to the stylesheet:

[hidden] { display: none; }