JavaScript interacts with it’s world which is the web page. The web page is also called the DOM. DOM stands for Document Object Model. It really is nothing more than a way we all agree to name elements on a web page, instead of calling the various parts of the page, “that doohickey thing.”
In this simple JavaScript program, I will provide an example of how to use JavaScript to navigate the web page (the DOM), to the h1 title, and then change the h1 title element on the page using one of the most popular JavaScript commands, “getElementByID.”
You can read a more technical description and additional information about the DOM on the Mozilla Developer Network.
Let’s break down this popular JavaScript command.
- document.getElementById
- Returns an object reference to the identified element.
The first part of the JavaScript command is the document interface. MDN describes it as follows, “The document interface represents any web page loaded in the browser and serves as an entry point into the web page’s content, which is the DOM tree. The DOM tree includes elements such as <body> and <table>, among many others.”
The second part of the JavaScript command is getElementById. This allows us to move through the html document until we find a section of the code with a specific ID. Just like we target an element in our html by its ID and then use CSS in order to change the color or change the layout position, we can also target an element by ID in our html in order to manipulate it with JavaScript.
What do I mean target by ID?
If your not familiar with an ID it is simply giving a element on a page a specific name. For example, a normal h1 tag would look like this.
<h1>This is a Title</h1>
We can assign an id to it by giving it a name, like this.
<h1 id="mainTitle">This is a Title</h1>
Now, for example, if I had multiple h1 tags in a web page, I could identify this specific one by its id or name, “mainTitle.” Then I could use the following simple two line JavaScript code to navigate to “mainTitle” assign what I found there to a variable called headline, and then replace that content with a completely different html string on my web page without re-loading the web page.
var headline = document.getElementById("mainHeading"); headline.innerHTML = "Wow, a New H1 Heading!";
Knowing the DOM and being able to navigate through the DOM is the single most important skill as a JavaScript developer.
See my Codepen.io example here.
Or, download the full code files from GitHub to practice with your own text editor.