What is the HTML DOM?
DOM stands for document object model. This basically is a standard for accessing and manipulating HTML elements in a document. The document object is used to grab these elements. We didn’t cover this when we were talking about the document object because this is a different topic in itself.
Basically, every single tag inside your document is considered an object. You’re allowed to have objects inside of objects. Since HTML tags are usually nested, this makes it a very complex tree of tags.
- Update and Grab all HTML elements in a page.
- Update and Grab all HTML attributes in a page.
- Update and Grab all CSS styles.
- React to certain events such as mouse clicks and hovers.
You already know how to use the document object. So, let’s expand on this with grabbing elements and changing stuff inside these elements. You already know how to write into the document itself, but what if you wanted to update the text inside a certain HTML element. Let’s learn how to do this.
We haven’t updated our HTML document in a while. Update your body tags to this.
<h1>This is a H1 Element!</h1>
<p>This is a paragraph.</p>
<p id="foo">This is a paragraph, too.</p>
<p class="foo">This is another paragraph.</p>
We have some elements with ids and classes. Let’s learn how to grab elements first. Clear up your script and add this bit of code.
var p = document.getElementsByTagName( 'p' );
The document object has a method named getElementsByTagName(). This method accepts 1 argument which is the name of the HTML tag you would like to grab. We store this in a variable named p. This is to shorten line of code whenever we need to grab this group of elements again.
Let’s now output the amount of <p> tags inside the HTML document. Add this line of code into your script.
document.write( p.length );
Doing this is the same thing as doing this.
document.write( document.getElementsByTagName( 'p' ).length );
We store it in a variable to make our code cleaner. Now, what if you wanted to grab a certain element? This is possible with IDs and classes.
In our next tutorial, I’ll teach you how to actually manipulate HTML tags. The HTML DOM basically converts all HTML tags into objects. Which we can then access using properties and methods. If you would like more information about the HTML getElementsbyTagName() method then go here.