Questions And Answers

More Tutorials

Javascript DOM API

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>

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

 <h1>Adding an element</h1>

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";

That will change your HTML body to the following:


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

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.


In this page (written and validated by ) you learned about Javascript DOM API . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Comments.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.