JS DOM Navigation & Nodes

DOM Navigation And Nodes

When you’re working with websites, the Document Object Model (DOM) represents the structure of the web page in a tree-like format. To work with this structure in JavaScript, you need to understand nodes and how to navigate them. This allows you to manipulate the content and structure of a page dynamically.

What is a Node in JavaScript?

In JavaScript, a node represents any part of the web page structure. Think of a node as a building block of a web page. Each node can be:

  1. The Document Node: Represents the entire HTML or XML document in the Document Object Model (DOM).
  2. Element Node: Represents HTML elements like <div>, <p>, <a>, etc. (These are the most common types of nodes).
  3. Text Node: Represents the text inside HTML elements. For example, the text “Hello World” inside a <p> tag is a text node.
  4. Attribute Node: Represents an attribute of an element. For example, the href attribute inside an <a> tag (<ahref=”https://example.com”>Link</a>) is an attribute node.

DOM Navigation

Once you know a node, you can navigate the DOM tree to access, modify, or manipulate these nodes using JavaScript. JavaScript provides several methods and properties to traverse the DOM.

Method Description Element Targeted Example
parentNode Selects the parent node of the current element. This is useful when you need to traverse the DOM tree. Parent Element let parent = element.parentNode;.
children Selects all child elements of the current element (excluding text nodes and comments). This is a live HTMLCollection. Child Elements let children = element.children;.
firstChild Selects the first child node of the current element. This can be a text node, element, or comment. First Child Node let firstChild = element.firstChild;
lastChild Selects the last child node of the current element. This can be a text node, element, or comment. Last Child Node let lastChild = element.lastChild;
previousSibling Selects the previous sibling node of the current element. Useful for traversing backward in the DOM tree. Previous Sibling Node let previous = element.previousSibling;.
nextSibling Selects the next sibling node of the current element. Useful for traversing forward in the DOM tree. Next Sibling Node let next = element.nextSibling;
firstElementChild Selects the first child element (ignores text nodes and comments) of the current element. First Child Element let firstElement = element.firstElementChild;
lastElementChild Selects the last child element (ignores text nodes and comments) of the current element. Last Child Element let lastElement = element.lastElementChild;
previousElementSibling Selects the previous sibling element (ignores text nodes and comments) Previous Sibling Element let previousElement = element.previousElementSibling;
nextElementSibling Selects the next sibling element (ignores text nodes and comments). Next Sibling Element let nextElement = element.nextElementSibling;

DOM Node

A node is a fundamental building block that represents every component of a document. Whether it’s an HTML tag, the text inside that tag, an attribute of an element, or even a comment, all of these are considered nodes in the DOM structure.

Properties of Node

Property Description Common Values Example
nodeType returns an integer that indicates the type of a given node. 1 (Element Node), 3 (Text Node), 8 (Comment Node), etc. let node = element.nodeType; console.log(node); Logs 1 for an element node.
nodeName returns the name of the node as a string. This is especially useful for element nodes, where it returns the tag name (e.g., “DIV”, “P”, “SPAN”) “DIV”, “P”, “TEXT”, “#document”, etc. let node = element.nodeName; console.log(node); Logs “DIV” for an element node.
nodeValue Returns the value of the node (text for text/comment nodes). null (for elements), “Hello” (for text), “This is a comment” (for comments). let node = textNode.nodeValue; console.log(node); Logs “Hello” for a text node.

Properties of Node

Methods Description Example
replaceChild(newNode, oldNode) Replace an old child node with a new one in the parent node. parentNode.replaceChild(newNode, oldNode);
appendChild(node) Appends a child node to the end of a specified parent node. parentNode.appendChild(childNode);
removeChild(node) Removes a specified child node from the parent node. parentNode.removeChild(childNode);
insertBefore(newNode, referenceNode) Inserts a new node before a reference node within the parent node. parentNode.insertBefore(newNode, referenceNode);
Example:

<body>
<h1>My Shopping List</h1>
<ul id=”shoppingList”>
<li>Apples</li>
<li>Bananas</li>
<li>Carrots</li>
</ul>
<script>
// Get a reference to the shopping list (ul)
const shoppingList = document.getElementById(‘shoppingList’);
// 1. Change the text of the first item in the list
let firstItem = shoppingList.firstChild; // First child node
while (firstItem && firstItem.nodeType !== 1) {
firstItem = firstItem.nextSibling; // Skip any text nodes or spaces
}
if (firstItem) {
firstItem.textContent = “Green Apples”; // Change the content of the first item
}
// 2. Change the text of the last item in the list
let lastItem = shoppingList.lastChild; // Last child node
while (lastItem && lastItem.nodeType !== 1) {
lastItem = lastItem.previousSibling; // Skip any text nodes or spaces
}
if (lastItem) {
lastItem.textContent = “Fresh Carrots”; // Change the content of the last item
}
// 3. Add a new item to the list
let newItem = document.createElement(‘li’); // Create a new <li> element
newItem.textContent = “Oranges”; // Set the content of the new item
shoppingList.appendChild(newItem); // Add the new item to the list
// 4. Remove the first item from the list
shoppingList.removeChild(shoppingList.firstChild); // Remove the first <li> element
</script>
</body>

This logs the Custom formatted date and time to the console, which is formatted according to the options passed in toLocaleString(). For example, “11/21/2024, 10:40 AM”.

Explanation:

1. Navigating Nodes:

  • We use firstChild and lastChild to find the first and last child nodes of the shoppingList. However, the list may contain extra text nodes (such as whitespace or line breaks). To get the actual <li> elements, we skip over these non-element nodes using a while loop.

2. Modifying Nodes:

  • Once we have the first and last <li> elements, we change their textContent to update the text inside them (e.g., changing “Apples” to “Green Apples” and “Carrots” to “Fresh Carrots”).

3. Adding a New Item:

  • We create a new <li> element using document.createElement(‘li’), set its textContent to “Oranges”, and append it to the list using appendChild.

4. Removing an Item:

We use removeChild to remove the first item in the list (shoppingList.firstChild).
Output:

Course Video

Practice Scenarios

1.  Navigating and Modifying the First List Item

Objectives:

  • Write JavaScript to navigate to the first item in the list and change its text to “Grapes”.
  • Use the appropriate DOM method to find the first list item.
  • Modify the text content of the first <li> element.

Here’s an example program:

<body>
<ul id=”myList”>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
<script>
let firstItem = document.getElementById(‘myList’).firstChild;
while (firstItem && firstItem.nodeType !== 1) {
firstItem = firstItem.nextSibling;
}
firstItem.textContent = “Grapes”;

Output:
Before:
After:

2.  Removing the Last List Item

Objectives:

  • Write JavaScript to remove the last item from the list (<li>Cheese</li>).
  • Use the correct DOM method to select the last list item.
  • Remove it from the list using the appropriate DOM manipulation method

Here’s an example program:

<body>
<ul id=”groceryList”>
<li>Milk</li>
<li>Bread</li>
<li>Cheese</li>
</ul>
<script>
let lastItem = document.getElementById(‘groceryList’).lastChild;
while (lastItem && lastItem.nodeType !== 1) {
lastItem = lastItem.previousSibling;
}
document.getElementById(‘groceryList’).removeChild(lastItem);
</script>
</body>

Output:
Before:
After:

3.  Adding a New Item to the List

Objectives:

  • Write JavaScript that will add a new list item at the end of the list, with the text “Finish homework”.
  • Use DOM methods to create a new <li>
  • Add it to the existing list as the last item

Here’s an example program:

<body>
<ul id=”todoList”>
<li>Do the laundry</li>
<li>Buy groceries</li>
<li>Talk to Team </li>
</ul>
<script>
let newItem = document.createElement(‘li’);
newItem.textContent = “Finish work”;
document.getElementById(‘todoList’).appendChild(newItem);
</script>
</body>

Output:
Before:
After:

4.  Prepending a New List Item

Objectives:

  • Add a new list item at the beginning of the list.
  • Create a new <li> element with the text “Call Mom”.
  • Insert it at the start of the <ul> list.

Here’s an example program:

<body>
<ul id=”todoList”>
<li>Do the laundry</li>
<li>Buy groceries</li>
<li>Talk to Team</li>
</ul>
<script>
let newItem = document.createElement(‘li’);
newItem.textContent = “Call Mom”;
document.getElementById(‘todoList’).insertBefore(newItem, document.getElementById(‘todoList’).firstChild);
</script>
</body>

Output:
Before:
After:

5.  Adding Multiple Items to the List

Objectives:

  • Add multiple items to the list at once
  • Create two new <li> elements.
  • Append both to the list with the id=”todoList”

Here’s an example program:

<body>
<ul id=”todoList”>
<li>Do the laundry</li>
<li>Buy groceries</li>
<li>Talk to Team</li>
</ul>
<script>
let newItem1 = document.createElement(‘li’);
newItem1.textContent = “Write code”;
let newItem2 = document.createElement(‘li’);
newItem2.textContent = “Read a book”;
document.getElementById(‘todoList’).appendChild(newItem1);
document.getElementById(‘todoList’).appendChild(newItem2);
</script>

Output:
Before:
After: