简体   繁体   中英

Why is style.display's value undefined?

What could be a reason for an element's style.display returning the value undefined ?

In my Javascript, I have an if statement checking

if (document.getElementById("myModal").style.display != 'none'){ 
    console.log("The pop up is visible.");
    do something
}

In my CSS, I have myModal set to display: none;

myModal is a pop up form that is accessed through click.

I moved my <script> for the js file to the bottom of the HTML, doesn't this ensure that my DOM is fully loaded before the javascript is run? However, the console.log displays as soon as the page is loaded even though the conditional is not met (ie the pop up is currently not visible).

Not sure if the Leaflet API has anything to do with this?

What you have in your CSS stylesheets has little to do with the style property of your element. The style property only includes inline styles. Notice how in this code the first div has an empty style.display , even though it is display: none because of the stylesheet; only the second and third div have style.display properties set to anything:

 const divs = document.querySelectorAll( 'div' ); [].forEach.call( divs, div => document.body.innerHTML += div.style.display + '<br>' ); 
 div { display: none; } 
 <h2>Divs:</h2> <div>One</div> <div style="display:none;">Two</div> <div style="display:block;">Three</div> <h2>Styles:</h2> 

If you want to get the computed style of an element, considering all stylesheets and inline styles, you can use getComputedStyle . Or you can just use jQuery:

if ( $('#myModal').is(':visible') ) {
    console.log("The pop up is visible.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM