0

I am creating a react app with createreactapp. I have this if statement that checks for the css display property of a div whose id is step1 as below:

const step1 = document.getElementById("step-1")  

    if (step1.style.display === 'block') {
                console.log("true")            
              } else {
                  console.log('false')
              }

The CSS style of the div is as follows:

    .step-1 {
           display: block;
        }

However, when I check the console, the if statement returns or console.logs 'false" when it should be 'true'.

The reason I simplified my actual issue this way is because I am trying to potentially hide the div based on the result of the if statement that checks the value of the CSS display property. However, it is not working. Not sure what is going on.

As for the html, it is a simple div with some content:

<div className="step-1" id="step-1">
 Some content ....
</div>
  • `step-1` is not equivalent to `step1`. Besides you define `step-1` as a class and thus your js is needed to see how you define `step1`. – GetSet Jan 06 '21 at 02:40
  • 2
    Unless there's an actual `style` attribute that sets `display` to `block` it won't be anything. CSS styles do not set the style object. – MinusFour Jan 06 '21 at 02:42
  • You should rather check for class existance: https://stackoverflow.com/questions/38795892/check-for-existence-of-classes-on-click-react – Beniamin H Jan 06 '21 at 02:43

1 Answers1

6

if (step1.style.display === 'block') { is checking the inline styles of step1, if you want to simply determine whether it currently has that style, you need to do

 const styles = window.getComputedStyle(step1);
 if (styles.getPropertyValue('display') === 'block') {
     // do something
 }
dave
  • 62,300
  • 5
  • 72
  • 93