Document Object Model
The Document Object Model
(DOM) is a representation of the structure of your HTML page that you can interact with programmatically. An HTML page is a hierarchy. The browser produces an outline based on the HTML hierarchy presented to it and displays this in the browser to the user. Behind the scenes, unknown to the user, the browser constructs a DOM. The DOM’s application programming interface (API) is exposed as objects with properties and methods, enabling you to write JavaScript code to interact with the HTML elements rendered to the page.
This notion is very powerful. You can add new elements to the page that didn’t even exist in your original HTML page. You can modify elements to change their behavior, layout, appearance, and content. Theoretically, although this is rarely a recommended practice, you could render a blank HTML page to the browser, build the entire page using JavaScript, and produce the exact same results. Having that power over your webpages is very exciting, even after they are rendered. You start by selecting items in the DOM to get a reference to them.
Selecting items in the DOM
To manipulate the DOM, you need to know how to access it and to obtain references to the elements you want to manipulate.
Note: The Document Object Model as a Family Tree
The DOM is essentially a collection of nodes arranged in a tree. All the nodes are related to each other. They are one big happy family of children, siblings, parents, grandparents, grandchildren, and so on. This essence of a family tree represents the hierarchy of the DOM and is important to understand as you manipulate the DOM through code.
You can access DOM elements through a global object provided by the browser, called document, or through the elements themselves after you obtain a reference to one.
Method | Usage description |
---|---|
getElementById | Gets an individual element on the page by its unique id attribute value |
getElementsByClassName | Gets all the elements that have the specified CSS class applied to them |
getElementsByTagName | Gets all the elements of the page that have the specified tag name or element name |
querySelector | Gets the first child element found that matches the provided CSS selector criteria |
querySelectorAll | Gets all the child elements that match the provided CSS selector criteria |
-
UpdatedJan 07, 2015
-
Views3,135