简体   繁体   中英

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?

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>

Change your html to this :

 <h1 id="header"></h1>
 <p id="p1"> </p>

And try your JavaScript code now they will work, because they are not empty elements.

I think the main issue you are having is with the way you are setting up the closing tags like so: <h1 id="header"/> with / instead of a closing statement. This is incorrect and you need to close it like so: <h1 id="header"></h1> The same is true for the <p> tag and many others. There are some exceptions to this rule which you can find here:

http://www.w3schools.com/html/html_elements.asp

Here is an example fiddle with the actual result!

http://jsfiddle.net/nd3Dq/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM