Skip to content
Steve Perry edited this page Oct 24, 2015 · 2 revisions

View the source code.

Use JavaScript to display Hello World.

JavaScript HTML DOM

When a web page is loaded, the browser creates a Document Object Model (DOM) of the page. The DOM is a tree of objects. The root object in the tree in named document. The document object has a getElementById method, which returns an Element object.

The JavaScript in this example gets an Element object that represents the <p id="par1"> element. Then it sets the innerHTML property of the Element object.

Note: This Stack Overflow post says that (until HTML5) innerHTML is not a property mentioned in any standard, but is supported by all major browsers. This Stack Overflow post discusses alternatives to using innerHTML.

The browser processes the page in order (I think). When the browser comes to the <script> element, it executes the JavaScript code inside. But at that point, the second paragraph hasn't been processed yet. So the innerHTML of the demo paragraph gets changed, but the innerHTML of the demo2 paragraph does not get changed.

<html>
<body>

<p id="demo">Filler</p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
document.getElementById("demo2").innerHTML = "Perry"
</script>

<p id="demo2">Steve</p>

</body>
</html>

Clone this wiki locally