Using the DOM API

suggest change

DOM stands for Document Object Model. It is an object-oriented representation of structured documents such as XML and HTML.

Setting the textContent property of an Element is one way to output text on a web page.

For example, consider the following HTML tag:

<p id="paragraph"></p>

To change its textContent property, we can run the following JavaScript:

document.getElementById("paragraph").textContent = "Hello, World";

getElementById returns null when the id is missing. When the element exists, this sets its text to “Hello, World”:

<p id="paragraph">Hello, World</p>

(See also this demo)

You can also use JavaScript to create a new HTML element programmatically. For example, consider an HTML document with the following body:

<body>
   <h1>Adding an element</h1>
</body>

In our JavaScript, we create a new <p> element whose text is “Hello, World” and add it at the end of the body:

const element = document.createElement('p');
element.textContent = "Hello, World";
document.body.appendChild(element); //add the newly created element to the DOM
console.log(element.textContent);

That will change your HTML body to the following:

<body>
   <h1>Adding an element</h1>
   <p>Hello, World</p>
</body>

The script must run after the element it uses has been parsed. Put the <script> after that markup, or listen for DOMContentLoaded, which fires when the document has been parsed. The load event waits for other resources as well, such as images.

A setTimeout of 0 does not guarantee that the rest of the document has been parsed. It only runs as a later task.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents