Introduction
JavaScript allows us to create dynamic interactive web applications. This is due to the Document Object Model (DOM) interface that represents the HTML document as a tree of nodes.
The HTML DOM Tree of Objects
An object in the DOM is called a node
. The DOM has some built-in nodes such as document
and document.body
and HTML element nodes such as <div>
or <p>
. A node can also be a textNode
, which refers to a text contained in an element such as <p>some text</p>
or a comment node for comments such as <!-- comment -->
. Below is a summary of the most commonly used node types in the DOM.
Node Type | Example |
---|---|
ELEMENT_NODE | Any HTML element such as <p> , <ul> , <div> , etc. |
ATTRIBUTE_NODE | Any attribute of an Element such as href in <a> or src in img |
TEXT_NODE | The actual text inside an Element or Attribute such as <p>text</p> or <img src="./some-image.png"> |
COMMENT_NODE | A Comment node as in <!-- this is a comment --> |
DOCUMENT_NODE | A Document node that represents any web page loaded in the browser |
Most web browsers use tabs and each tab is represented by its own Window
object.
Each window
object has a document
property that refers to the DOM, which represents the content of the window. The DOM enables creating interactive web pages, where we can add, change, or delete any HTML elements and attributes, CSS styles, or events dynamically. We will explore the main parts of the DOM API that enable these capabilities.
Below is an example of how an HTML document is represnted in the DOM tree:
<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
</head>
<body>
<div class="content">
<ul id="menu">
<li>Home</li>
<li>About</li>
</ul>
</div>
</body>
</html>
How to query or select individual elements from a document?
We can query for elements using:
- Element Id values
document.getElementById(id)
- Element tag names
document.getElementsByTagName(name)
- Element names
document.getElementsByName(name)
- CSS selectors
document.querySelector(selectors)
anddocument.querySelectorAll(selectors)
1. Using document.getElementById
The Document method document.getElementById(id)
returns an Element that matches the given id value.
Console Output:
Title 1
2. Using document.getElementsByTagName
The Document method document.getElementsByTagName(name)
returns a NodeList
of Elements that match the given Element tag name (e.g., p
, h1
, table
, etc.).
Console Output:
Title 1
Title 2
3. Using document.getElementsByName
The Document method document.getElementsByName(name)
returns a NodeList
of Elements that match the given name attribute (e.g., name="hobby"
).
|
|
Console Output:
Volleyball
Football
Basketball
Tennis
4. Using document.querySelector()
or document.querySelectorAll()
We can also use CSS selectors for describing elements or sets of elements within a document. The Document methods document.querySelector()
and document.querySelectorAll()
allow us to find elements if they match the given CSS selector.
document.querySelector()
returns the first Element that matches the specified CSS selector.document.querySelectorAll()
returns aNodeList
of all Elements that match the specified CSS selector.
Please refer to the previous lecture notes on CSS selectors for usage and syntax.
Note: Many browsers won’t match for psudeo-selectors (e.g.,
:visited
) and psudeo-elements (e.g.,::first-line
) when used withdocument.querySelector()
ordocument.querySelectorAll()
for the privacy of users as this may expose their browsing history.
|
|
Console Output:
Using document.querySelector()
Link #1, in the div.
Using document.querySelectorAll()
Link #1, in the div.
Link #2, in the div.
How to modify the style of any document element?
We can use the document methods above to get elements and change their style in the form of element.style.<cssProperty>
, where the CSS property’s name is specified in a camelCase form
As a general rule of thumb, in order to get the style property name in JavaScript, you should change any hyphenated CSS property’s name to camelCase.
css property JavaScript property background-color backgroundColor margin-top marginTop text-decoration textDecoration color color
Below is an example on how to change the background of a <div>
element in JavaScript:
document.getElementsByTagName("div")[0].style.backgroundColor = "red";
How to add or change attributes of any document element?
We can use the document methods above to query or get elements and change their attributes in the form of element.<attribute_name>
as shown below:
<a id="myLink" href="#">CPIT-405</a>
<script>
document.getElementById("myLink").href= "https://cpit405.gitlab.io/";
</script>
How to query, set, and modify the content of a document?
We can use the document methods above to query or get elements and change their content using element.innerText
, to get or set the rendered text of an element node and its descendants or element.innerHTML
, which is used to get or set the HTML markup contained within the element.
<a id="myLink" href="https://cpit405.gitlab.io/"></a>
<div id="codeBlock"></div>
<script>
document.getElementById("myLink").innerText = "CPIT-405";
document.getElementById("codeBlock").innerHTML =
`<ul id="list">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>`;
</script>
How to traverse a document? How to find the ancestors, siblings, and descendants of an element?
Once an element is selected (e.g., using document.getElementById()
), we can traverse the element and its children using .children
, .firstElementChild
, .nextElementSibling
, lastChild
, etc. Below is an example that shows how to traverese the DOM to apply a 20% discount to the prices of a list of items.
|
|
|
|
How to find the closest element to an element?
We can use the element’s .closest()
method to traverse the Element and its parents (moving up the DOM tree toward the document root) until it finds a node that matches the given selector string.
Suppose we want to style the closest ul
element to a list of items on a page that has multiple nested ul
elements:
How to modify the structure of a document by creating, inserting, and deleting nodes?
Creating and inserting new elements
We can use document.createElement
to create an HTML element and document.createTextNode
to create a text node for the text value inside of an element. We can also use <Element>.appendChild
to add a node to the end of the list of children of a parent node.
How to insert text before or after an element or an element’s text using insertAdjacentText
?
We can use insertAdjacentText(where, text)
to insert text before an element, at the beginning of the element’s text, at the end of the element’s text, or after the element itself. The insertAdjacentText
method takes a position relative to the element and a text value. The following are the possible positions:
position | Description |
---|---|
beforebegin | Before the element itself. |
afterbegin | Inside the element but before its first child. |
beforeend | Inside the element but ater its last child. |
afterend | After the element itself. |
<!-- beforebegin -->
<p>
<!-- afterbegin -->
text value
<!-- beforeend -->
</p>
<!-- afterend -->
Example:
How to insert HTML before or after an element or an element’s child nodes using insertAdjacentHTML
?
The insertAdjacentHTML(where, text)
is like the insertAdjacentText
but with inserting HTML as a string instead of text.
How to delete a document element from the DOM tree?
We can use the elemen’ts .remove()
method to remove elements from the DOM tree.