Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In HTML/JavaScript, how do you dynamically set a header/paragraph element's text without overwriting anything else?

When you search for how to set a paragraph or header element's text dynamically, you keep coming across pretty much the same line of code:

document.getElementById("header").innerHTML = "some text";

This isn't entirely correct though. Take the following example:

<html>
    <head />
    <body>
        <h1 id="header" />
        <p id="p1" />
        <script type="text/javascript">
            document.getElementById("header").innerHTML = "header";
            document.getElementById("p1").innerHTML = "p1";
        </script>
    </body>
</html>

The first JavaScript line pretty much deletes p1 from the page, even though p1 and header have nothing to do with each other in the raw HTML. When wrapping the second JavaScript line in a try...catch block, the error that's caught is:

document.getElementById(...) is null

The same problem exists when you use textContent instead of innerHTML. I'm a little surprised that everybody is saying that this is how you're supposed to change the text of an element when it really doesn't suit that purpose very well. What's the right way to set this up?

like image 795
Panzercrisis Avatar asked Jan 21 '26 10:01

Panzercrisis


1 Answers

p and h1 are not "empty elements", meaning they're not closed in the same tag that opens them (like img and br). If you write them like that, they're not valid tags and the browser will ignore them (which is why document.getElementById can't find them). Try this instead:

<html>
    <head></head>
    <body>
        <h1 id="header"></h1>
        <p id="p1"></p>
        <script type="text/javascript">
            document.getElementById("header").innerHTML = "header";
            document.getElementById("p1").innerHTML = "p1";
        </script>
    </body>
</html>