The power of JavaScript is its use in dynamically displaying and manipulating elements on a webpage written in HTML. We know that an HTML page consists of elements such as <head><body> <h1> tags or text fields and buttons. The DOM or Document Object Model represents the structure of these elements as a "tree" data structure after your web browser reads a page. The DOM Application Programming Interface (API) contains methods that provide JavaScript access to these elements. Start by reading this article to learn about the document structure of the DOM and how to find, create and change elements.
DOM nodes contain a wealth of links to other nearby nodes. The following diagram illustrates these:
Although the diagram shows only one link of each type, every node has a parentNode
property that points to the node it is part of, if any. Likewise, every element node (node type 1) has a childNodes
property
that points to an array-like object holding its children.
In theory, you could move anywhere in the tree using just these parent and child links. But JavaScript also gives you access to a
number of additional convenience links. The firstChild
and lastChild
properties point to the first and last child elements or have the value null
for nodes without children. Similarly, previousSibling
and nextSibling
point
to adjacent nodes, which are nodes with the same parent that appear immediately before or after the node itself. For a first child, previousSibling
will be null, and for a last child, nextSibling
will
be null.
There's also the children
property, which is like childNodes
but contains only element
(type 1) children, not other types of child nodes. This can be useful when you aren't interested in text nodes.
When dealing with a nested data structure like this one, recursive functions are often useful. The following function scans a document
for text nodes containing a given string and returns true
when it has found one:
function talksAbout(node, string) { if (node.nodeType == Node.ELEMENT_NODE) { for (let child of node.childNodes) { if (talksAbout(child, string)) { return true; } } return false; } else if (node.nodeType == Node.TEXT_NODE) { return node.nodeValue.indexOf(string) > -1; } } console.log(talksAbout(document.body, "book")); // → trueThe
nodeValue
property of a text node holds the string of text that it represents.