1

I'm a little confused about the display: none property. Many articles ob the internet says that with display property set to none an element is not in the DOM tree. And that's the difference from opacity: 0 and visibility: hidden which won't remove an element from the DOM and just make it invisible.

From https://stackoverflow.com/a/4718378/20395932

Because display: none actually removes the elements from the DOM. visibility: hidden merely makes them invisible, but they're still there.

From https://blog.kevinchisholm.com/css/visibility-hidden-vs-display-none/

This is an important detail because with display:none, you are effectively removing the element from the DOM.

Also I read that

The browser will not response to any events of element which uses either display: none or visibility: hidden.

But in React I set a ref to an element, set it's display porperty to none... and I still see that element in DOM in dev tools. Also I can call on-click handlers of this element via the ref. Also I don't understand how display: none can remove any element from the DOM if it's just a CSS property and can't realy manipulate DOM.

As far as I understand the element with display: none is still in the DOM but it's just not rendered. But what about responsing to events?

forty5
  • 63
  • 4

1 Answers1

3

,,, with display property set to none an element is not in the DOM tree.

That's just wrong.

An element with display property set to none generates no box in the box tree. All descendant nodes in the DOM document also generate no boxes or text runs in the box tree.


In detail, display:none is somewhat magical. As well as generating no boxes for the DOM document sub-tree, it trumps positioning and floating in a way that other display properties don't, hides the entire DOM document sub-tree from the accessibility API, affects the processing of animations, probably other related stuff.

But it does not remove the element from the DOM document, nor remove or disable the event listeners or handlers from the element. But of course, since there's nothing rendered for the sub-tree, user interaction cannot fire events on those elements.

Alohci
  • 78,296
  • 16
  • 112
  • 156
  • but about events of such element? – forty5 Nov 20 '22 at 23:28
  • 1
    user can't interact with it so no user triggered events will fire. – epascarello Nov 21 '22 at 00:36
  • 1
    It also has a few implications on the HTML side, basically the references to https://html.spec.whatwg.org/multipage/rendering.html#being-rendered with the most impressive one IMM: content is unloaded when display:none, which could be said as actually affecting the DOM. Also, there can be events fired on hidden elements, for instance `oninvalid` would fire on hidden when its parent
    is submitted.
    – Kaiido Nov 22 '22 at 02:45