Element by Their ID
Object in this section You’ll learn a lot about navigating around the DOM using the various methods of the document object. For now, we limit ourselves to looking at one in particular—the getElementById() method.
To select an element of your HTML page having a specific ID, all you need to do is call the document object’s getElementById() method, specifying as an argument the ID of the required element. The method returns the DOM object corresponding to the page element with the specified ID.
<div id="div1"> ... Content of DIV element ... </div>
In your JavaScript code, you can access this <div> element using getElementById(), passing the required ID to the method as an argument:
var myDiv = document.getElementById("div1");
We now have access to the chosen page element and all of its properties and methods.
The innerHTML Property
A handy property that exists for many DOM objects, innerHTML allows us to get or set the value of the HTML content inside a particular page element. Imagine your HTML contains the following element:
<div id="div1"> ... Content of DIV element ... </div>
We can access the HTML content of the
var myDivContents = document.getElementById("div1").innerHTML;
The variable myDivContents will now contain the string value:
"<p>Here is some original text.</p>"
We can also use innerHTML to set the contents of a chosen element:
document.getElementById("div1").innerHTML = "<p>Here is some original text.</p>";
Executing this code snippet erases the previous HTML content of the <div> element and replaces it with the new string.