javascripthtmlcss

Not able to change style.display with javascript


First time I've posted a coding question on here. I've nearly completed a JS/HTML/CSS game and will be uploading to Steam soon. Long story short, I've run into a snag, needing to move all inline styles in HTML into an external css file. In doing this, my working code seems to have broken. I've boiled it down to this question: Why does the button in the code below not display the div? With all styling moved to an external CSS file, how can I get javascript lines such as document.getElementById("id").style.display = "" to work with minimal adjustments to my thousands of lines of code?

CSS:

#testID {
    display: none;
}

HTML:

<div id="testID">
    1234
</div>
<div>
    <button onclick="showFn()">Show</button>
</div>

Javascript:

function showFn() {
  document.getElementById("testID").style.display = ""
}

Solution

  • It would be better to use a class, because then all your style information stays in the stylesheet. If your Javascript changes the style directly, then you have some of your style information in the stylesheet, and some in Javascript ... this makes your code harder to maintain.

    function showFn() {
      document.getElementById('testID').classList.remove('hidden')
    }
    .hidden {
      display: none;
    }
    <div id="testID" class="hidden">
        1234
    </div>
    
    <div>
        <button onclick="showFn()">Show</button>
    </div>