Hiding an element: Difference between Javascript attribute and CSS style Hiding an element: Difference between Javascript attribute and CSS style javascript javascript

Hiding an element: Difference between Javascript attribute and CSS style


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; }


The difference between these two lines of code is that one of them adds an attribute to the element with the given value, while the other sets a property within the style declaration.

For instance:

Let's say that your element variable was a div. When you call

element.setAttribute("hidden", true);

The elements will now look like this:

<div hidden="true"></div>

When you call

element.style.visibility = "hidden";

You will get:

<div style="visibility: hidden;"></div>