Search code examples
javascripthtmlgetelementbyid

How to delete the contents of a paragraph with javascript


I have a paragraph that I'd like to delete the contents of.

document.getElementById(id).innerHTML = "";

doesn't seem to be working. Does anyone have a better solution?

Here's an example

<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("p").innerHTML = "";
</script>
</head>
<body>
<p id="p">
words
</p>
</body>
</html>

but the words in the paragraph are not removed. Thanks in advance to anyone that can help.


Solution

  • <!DOCTYPE html>
    <html>
    <head>
    <!-- here the p tag doesn't exist yet -->
    <script>
    document.getElementById("p").innerHTML = "";
    </script>
    </head>
    <body>
    <p id="p">
    words
    </p>
    
    <!-- however here it does exist -->
    </body>
    </html>
    

    how to fix it ?

    // only use this if you can't move your javascript at the bottom
    window.onload = function() {
        document.getElementById("p").innerHTML = "";
    }
    

    or move your javascript at the end of the page (this is the preferred one as javascript should always be loaded at the end of the page)

    <!DOCTYPE html>
    <html>
    <head>
    <!-- here the p tag doesn't exist yet -->
    
    </head>
    <body>
    <p id="p">
    words
    </p>
    
    <!-- however here it does exist -->
    <script>
    document.getElementById("p").innerHTML = "";
    </script>
    </body>
    </html>