Home > OS >  Can't console.log() .style.display information
Can't console.log() .style.display information

Time:05-27

I'm able to correct switch between a dropdown menu being displayed and hidden when I click on my input tag, but when console logging the style displayed I get nothing shown on the console. What is the explanation for not being able to see this and how would I go about trying to correctly see which display style I used?

document.getElementById('search').addEventListener("click", function () {
    const grid1 = document.querySelector(".modal");
    grid1.style.display = grid1.style.display ? "none" : "flex";
    console.log(grid1.style.display);
});

CodePudding user response:

Instead of using 'yourelement.style.display' use 'getComputedStyle' function to get the value of any property in this case 'display', thats because Computed style contains all the CSS properties set to an element. Even if do not set a property to an element. You will still find that property in the computed styles.

Modifiying your code with 'getComputerStyle'

document.getElementById('search').addEventListener("click", function () {
    const grid1=document.querySelector(".modal")

    console.log(window.getComputedStyle(grid1).display)
    grid1.style.display = window.getComputedStyle(grid1).display == "none" ? "flex" : "none";
    console.log(window.getComputedStyle(grid1).display)
 })
.modal {
  display: none;
}
<input id="search">
<select ></select>

For more clarification check Window.getComputedStyle() in MDN Web Docs

  • Related