The Document Object Model - TristanVarewijck/Block-Tech GitHub Wiki

Data structures

We call a data structure a 'tree' when it has a branching structure. In the case of the DOM, document.documentElement serves as the root. a typical tree has different kind of nodes some tree's have indentifiers values and application nodes > application nodes may have children, whereas identifiers and values are leaves, or nodes without children

The same goes for the DOM the body has sections in these sections are children wich are paragraphs. Those paragraphs can have a link in it or have no children.

Tree

DOM nodes contain a wealth of links to other nearby nodes, in theory you could move anywhere in the tree only using parent and child links but javascript also offers firstChild and lastChild wich selects the firstChild and lastChild elements. Navigating these links among parents, children, and siblings is often useful But if we want to find a specific node in the document, reaching it by starting at document.body and following a fixed path of properties is a bad idea if we for example want the first 'a' tag in the dom we could say:

let link = document.body.getElementsByTagName("a")[0];

But if want to select a element by ID we can do this:

let link = document.body.getElementByID("important-link"); 

A similar method is document.body.getElementByClassName("className");

Nodes

Say we want to write a script that replaces all images ( tags) in the document with the alt text of those images. For that we can create a node! Text nodes are created with the document.createTextNode method.

Styling

The way a document is displayed can be influenced by styling, both by attaching styles to nodes directly and by defining rules that match certain nodes. There are many different style properties, such as color or display.

Query selectors

The querySelectorAll method, which is defined both on the document object and on element nodes, takes a selector string and returns a NodeList containing all the elements that it matches.

The querySelector method (without the All part) works in a similar way. This one is useful if you want a specific, single element. It will return only the first matching element or null when no element matches.

Resource

⚠️ **GitHub.com Fallback** ⚠️