The DOM Tree
The Document Object Model (DOM) is an interface that treats an HTML document as a tree-like structure each node contains an object that represents a part of the document. Each branch of the DOM tree ends with an element node. Some methods allow programmatic access to the tree, with these methods you can change the structure, style, and content of a document. The node elements can have event handlers attached to them, once the event fires off, the event handlers automatically get executed.
This is an example —
A DOM starts at but what’s visible to the DOM starts from what’s in between the element. Anything that is within the<body>
element is considered subtrees.
And the tree for the example above will look something like this —
You can find and select an HTML element on the rendered page
When creating an HTML for a page on your application, its very useful to use metadata for a node element. Metadata is a class
or id
— the attribute makes it easier to find the node. If you make the metadata specific its more helpful to find the desired element.
The methods to find an element —
document.getElementsByClassName()
This method is used more commonly in DOM programming. This method finds the elements by the class name.
document.getElementById()
This method finds elements by its ID. All ID’s are expected to be unique.
You can try out these methods by opening up your DevTools and find the elements by its id or class name by typing the following in —
document.getElementById(‘the ID’)
You can see a full list of methods here.
Conclusion
Knowing how to navigate any DOM tree makes it easy to find node elements and manipulate them in JavaScript.