seanbulley
seanbulley

Reputation: 15

JavaScript document.getElementById().innerHTML = "" not working

I'm looking to clear the content within a <div> but if I run the code it doesn't work. New to JS and would love a hand from someone who knows how it works!

Code as is:

<html>
<head>
    <!-- Javascript -->
    <script type="text/javascript">

        //UpdatesPlayerRoster
        function refreshRoster(){
            document.getElementById('roster').innerHTML = "";
        }
    </script>
</head>
<body>

    <div id=bodyContainer class="bodyContainer">
    <div id=playerListContainer class="playerListContainer">
        <div id=playerListHeader class="playerListHeader"><span class="playerListHeaderText">Players</span></div>
        <div id=playerListBody class="playerListBody">
        <table>
        <div id=roster>
            <tr><td>CONTENT TO BE CLEARED</td></tr>
        </div>
        </table>
    </div>

    <a href="#" onClick = "refreshRoster()">Refresh</a>
    </div>

</body>

Upvotes: 1

Views: 4081

Answers (2)

user295583058
user295583058

Reputation: 104

Here, try this:

<html>
<head>
    <!-- Javascript -->
    <script type="text/javascript">

        //UpdatesPlayerRoster
        function refreshRoster(){
            document.getElementById('roster').innerHTML = "";
        }
    </script>
</head>
<body>

    <div id="bodyContainer" class="bodyContainer">
    <div id="playerListContainer" class="playerListContainer">
        <div id="playerListHeader" class="playerListHeader"><span class="playerListHeaderText">Players</span></div>
        <div id="playerListBody" class="playerListBody">

            <div id="roster">
                <table>
                    <tr><td>CONTENT TO BE CLEARED</td></tr>
                </table>
            </div>
        </div>

        <a href="#" onClick = "refreshRoster()">Refresh</a>
    </div>

</body>

You need the <table> element to be inside of the div for it to work properly as browsers will correct this by itself. If you look at the page through inspect element, you'll see the browser has moved the table out of the div, which is why your code did not clear anything.

Alternatively, as the other answer states, you can use <tbody> instead of the <div>.

Upvotes: 0

Quentin
Quentin

Reputation: 943230

Your HTML is invalid. Use a validator.

You can't have a <div> element as a child element of a <table>.

Your browser is, most likely, performing error recovery by moving the <div> so it appears after the table and leaving the <tr> behind. It doesn't have any content to start with, so when you empty it with JS, it makes no difference.

Use a <tbody> instead of a <div>.

Upvotes: 7

Related Questions