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?
Completely hiding elements can be done in 3 ways: via the CSS property display , e.g. display: none; via the CSS property visibility , e.g. visibility: hidden; via the HTML5 attribute hidden , e.g. <span hidden>
Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”.
display:none means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). ... visibility:hidden means that unlike display:none , the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.
Using Css style we can hide or show HTML elements in javascript. Css provides properties such as block and none to hide/show the HTML elements.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With