Working with the Contents of Elements to Code with JavaScript

By Chris Minnick, Eva Holland

In JavaScript, 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.

Changing the properties of elements in a web document in order to reflect them instantly in the browser, without needing to refresh or reload the web page, is a cornerstone of what used to be called web 2.0.

innerHTML

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:

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

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.firstChild.innerHTML;
document.write (getTheInner);

In the preceding code, the value that will be output by the document.write() 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.firstChild.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.firstChild.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.