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.
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!”;
To set the value of an HTML attribute, you can use the setAttribute() method:
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”.