How to check if an element is visible with Javascript?

Asked

Viewed 64 times

-2

I hid a div using a CSS file and then tried to check if the div was visible or not with Javascript, my code did not return anything. Code used:
document.getElementById("load-content-endereco").style.display
Soon after I tried to add the CSS directly to the div, as follows:
<div id="load-content-endereco" style="display:none;">Conteúdo aqui</div>
And that way the code worked.
I tried to search the term on several websites and all used the same example, always adding CSS directly in the div with the attribute style.
Basically I seek to take values and manipulate the CSS that are in CSS files inside and outside my server.
Could someone give me a light here? I appreciate!

  • face you have to make a logic, maybe with if Else to see if you are with .style.display = 'none' etc. Actually did not understand good what you really intend to do...

  • This answers your question? How to display/hide an element in Javascript

  • I didn’t quite understand your question, could I explain it better, please?

  • I just need the amount display received at the time of verification. , I am setting this value in a CSS file (.../css/style.css). I know by adding CSS directly to div with style attribute (style="display: none;") I’ll have my result. But this is correct?

1 answer

1


This is the expected behavior.

As you are setting the property via CSS, this value will not be available when trying to get it using Javascript elemento.style.display (unless you define this value, as you said you have done). You must use Window.getComputedStyle() for this:

const div = document.querySelector('div');
const display = window.getComputedStyle(div, null).display;

console.log(`Valor da propriedade display: ${display}`);
div { display: none }
<div>Elemento</div>

  • Thank you very much, you helped me a lot.

  • getComputedStyle I didn’t even know there was such a thing as :D+1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.