Goran
Goran

Reputation: 748

How come that javascript reads element that has display:none?

For example if we have:

<style>
.child {display:none;}
</style>

<script>
$('.parent:contains("Invisible")').addClass('newparent');
</script>

<div class="parent">
   <div class="child">Invisible</div>
</div>

This code works! Parent div will receive new class newparent. This has no logic to me because I always believed if I put display:none that this is it, element is gone. You can't find it in inspect element, view source, etc.

But obviously this is not the case if javascript can find it. That means that this element is rendered somehow. So I'm wondering if element with display:none is still out there is it affecting performance? For example if we have right sidebar and we decide to hide it on mobile with display:none.

From experience I know that the site will load faster if sidebar has display:none, but question is still the same, what happens to the element with display:none, is it rendered somehow, if yes how and where?

Upvotes: 0

Views: 1690

Answers (2)

David
David

Reputation: 218960

I always believed if I put display:none that this is it, element is gone. You can't find it in inspect element, view source, etc.

Your assumption is incorrect. The element is still part of the DOM. It's just styled to not be rendered visibly on the screen.

So I'm wondering if element with display:none is still out there is it affecting performance?

No more than any other element would. If you have so many elements as to affect performance, then you'd certainly want to address that. But it has little to do with the styling.

what happens to the element with display:none, is it rendered somehow, if yes how and where?

It's part of the structure of the DOM in memory. Everything about it is still there. It's just not visibly shown in the viewport.

CSS styling doesn't change the structure of the HTML. It just governs how that structure is visibly displayed on the screen. (Or in some other medium.) JavaScript, on the other hand, can be used to modify the DOM in-memory, and those changes are also reflected in the display. (As your test demonstrates.)

Upvotes: 1

aw04
aw04

Reputation: 11187

You seem to have some misconceptions about display:none. It is a css property which causes the element to take up no room on the page. The element is still rendered and still exists all the same.

MDN display

Upvotes: 4

Related Questions