Using the DOM API

Download javascript eBook

Example

DOM stands for Document Object Model. It is an object-oriented representation of structured documents like 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";

This will select the element that with the id paragraph and set its text content 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> tag with a textContent property of and add it at the end of the html body:

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

That will change your HTML body to the following:

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

Note that in order to manipulate elements in the DOM using JavaScript, the JavaScript code must be run after the relevant element has been created in the document. This can be achieved by putting the JavaScript <script> tags after all of your other <body> content. Alternatively, you can also use an event listener to listen to eg. window's onload event, adding your code to that event listener will delay running your code until after the whole content on your page has been loaded.

A third way to make sure all your DOM has been loaded, is to wrap the DOM manipulation code with a timeout function of 0 ms. This way, this JavaScript code is re-queued at the end of the execution queue, which gives the browser a chance to finish doing some non-JavaScript things that have been waiting to finish before attending to this new piece of JavaScript.

Stats

Contributors: 37
2017-08-02
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook