Skip to content
Advertisement

java getelementbyid set to a variable

i have a simple function

function myFunction(id) {
        var e = document.getElementById(id);
        if (e.style.display === "block") {
            e.style.display = "none";
        }
    }

but for some reason, when i call the function, i get an error that says that i cant know what style null is. i want the x button to close the “window” when clicked, but it wont to do that.

css:

        body{
            background-color: black;
            font-family: 'arial';
        }
        .draggable {
            position: absolute;
            z-index: 9;
            background-color: #f1f1f1;
            text-align: center;
            border: 1px solid #d3d3d3;
            size: 100%
        }
        .title {
            z-index: 9;
            background-color: #f1f1f1;
            
        }
        p{
            text-align: left;
            margin: 2px;
            margin-left: 5px;
        }
        button{
            margin-right: 5px;
        }

html:

    <div id="div1" class="draggable">
        <div class="title">
            <p><button onclick="myFunction('div1');">X</button>timer</p>
        </div>
        <iframe src="timer.html" title="description" height="620px" width="1300px"></iframe>
    </div>
    <div id="div2" class="draggable">
        <div class="title">
            <p><button onclick="myFunction('div2');">X</button>tetris</p>
        </div>
        <iframe src="games/tetris.html" title="description" height="650px" width="340"></iframe>
    </div>

js

    function myFunction(id) {
        var e = document.getElementById(id);
        if (e.style.display === "block") {
            e.style.display = "none";
        }
    }

Advertisement

Answer

You have to set the initial value of style.display in your divs, try this:

function myFunction(id) {
        var e = document.getElementById(id);
        if (e.style.display == "block") {
            e.style.display = "none";
        }
}
<input type=text id="input" style="display: block">
<button onclick="myFunction('input')">Click!</button>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement