Web browsers are very complicated pieces of software with a lot of moving parts, many of which can’t be controlled or manipulated by a web developer using JavaScript. You might think that such limitations are a bad thing, but browsers are locked down for good reasons, mostly centering around security. Imagine if a web site could get access to your stored passwords or other sensitive information, and log into websites as if it were you?
Despite the limitations, Web APIs still give us access to a lot of functionality that enable us to do a great many things with web pages. There are a few really obvious bits you’ll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages:
This page will focus mostly on manipulating the document specifically.
The document currently loaded in each one of your browser tabs is represented by a document object model. This is a “tree structure” representation created by the browser that enables the HTML structure to be easily accessed by programming languages — for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the DOM with JavaScript after the page has been rendered.
Let’s look at a simple example page “dom-example.html”. Try opening this up in your browser — it is a very simple page containing a <section> element inside which you can find an image, and a paragraph with a link inside. The HTML source code looks like this:
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |
The DOM on the other hand looks like this:
Note: This DOM tree diagram was created using Ian Hickson’s Live DOM viewer.
You can see here that each element and bit of text in the document has its own entry in the tree — each one is called a node.
You will also encounter various terms used to describe the type of node, and their position in the tree in relation to one another:
It is useful to familiarize yourself with this terminology before working with the DOM, as a number of the code terms you’ll come across make use of them. You may have also come across them if you have studied CSS (e.g. descendant selector, child selector).
Please also read the following to further familiarize yourself with the DOM;