JavaScript Tutorials

Working with the Contents of Elements

You can display node types and node values by using the HTML DOM. You also can set property values of elements within the DOM using the Element object. When you use JavaScript to set the properties of DOM elements, the new values are reflected in real‐time within the HTML document.


The most important property of an element that you can modify through the DOM is the innerHTML property. The innerHTML property of an element contains everything between the beginning and ending tag of the element. For example, in the following code, the innerHTML property of the div element contains a ‘p’ element and its text node child:

    <p>This is some text.</p>

It’s very common in web programming to create empty div elements in your HTML document and then use the innerHTML property to dynamically insert HTML into the elements. To retrieve and display the value of the innerHTML property, you can use the following code:

var getTheInner = document.body.firstElementChild.innerHTML;

In the preceding code, the value that will be output by the console.log() method is:

<p>This is some text.</p>

Setting the innerHTML property is done in the same way that you set the property of any object:

document.body.firstElementChild.innerHTML = "Hi there!";

The result of running the preceding JavaScript will be that the p element and the sentence of text in the original markup will be replaced with the words “Hi There!” The original HTML document remains unchanged, but the DOM representation and the rendering of the web page will be updated to reflect the new value. Because the DOM representation of the HTML document is what the browser displays, the display of your web page will also be updated.

Setting attributes

To set the value of an HTML attribute, you can use the setAttribute() method:

document.body.firstElementChild.innerHTML.setAttribute("class", "myclass");

The result of running this statement is that the first child element of the body element will be given a new attribute named “class” with a value of “myclass”.


Create a h1 element and put the text “Hello World” into it using DOM

      document.body.firstElementChild.innerHTML = 'Hi there!';

Create a paragraph element with some text and apply a CSS class to it using DOM.