Trees and Branches
HTML is an XML-like structure in that the elements form a structure of parents’ nodes with children, like the branches of a tree. There is one root element (
html) with branches like
body, each with their own branches. For this reason, the DOM is also called the DOM tree.
document object is used. It’s provided by the browser and allows code on the page to interact with the content.
Getting an Element
The first thing to know is how to get an element. There are a number of ways of doing it, and browsers support different ones. Starting with the best supported we’ll move through to the latest, and most useful, versions.
document.getElementById is a method for getting hold of an element - unsurprisingly - by its ID.
var pageHeader = document.getElementById('page-header');
The pageHeader element can then be manipulated - its size and color can be changed, and other code can be declared to handle the element being clicked on or hovered over. It’s supported in pretty much all the browsers you need to worry about.
By Tag Name
document.getElementsByTagName works in much the same way as
getElementById, except that it takes a tag name (
li, etc) instead of an ID and returns a NodeList, which is essentially an array of the DOM Elements.
By Class Name
document.getElementsByClassName returns the same kind of NodeList as
getElementsByTagName, except that you pass a class name to be matched, not a tag name.
By CSS Selector
A couple of new methods are available in modern browsers that make selecting elements easier by allowing the use of CSS selectors. They are
var pageHeader = document.querySelector('#header'); var buttons = document.querySelectorAll(.btn);
getElementById, returns only one element whereas
querySelectorAll returns a NodeList. If multiple elements match the selector you pass to
querySelector, only the first will be returned.