Skip to content

Manipulating the DOM

Manipulating the DOM involves several key operations on the tree structure of HTML documents. Here are the primary actions you can perform:

Operations on DOM Nodes

  1. Update: Change the content of a DOM node.
  2. Traverse: Navigate through the child nodes of a DOM node.
  3. Add: Insert new child nodes within a DOM node.
  4. Delete: Remove a DOM node and all its children from the document.

Selecting DOM Nodes

To manipulate a DOM node, you first need to select it using methods like:

  • document.getElementById(): Returns a unique element by its ID.
  • document.getElementsByTagName(): Returns a collection of elements by tag name.
  • document.getElementsByClassName(): Returns a collection of elements by class name.
  • querySelector() and querySelectorAll(): Use CSS selectors for more precise selections.

Example Selections:

javascript
// Select the node with ID 'test'
let test = document.getElementById('test');

// Select all 'tr' elements within 'test-table'
let trs = document.getElementById('test-table').getElementsByTagName('tr');

// Select elements with class 'red' within 'test-div'
let reds = document.getElementById('test-div').getElementsByClassName('red');

// Get all direct children of 'test'
let cs = test.children;

// Get the first and last child of 'test'
let first = test.firstElementChild;
let last = test.lastElementChild;

Using querySelector and querySelectorAll

These methods offer a more flexible way to select nodes:

javascript
// Select the node with ID 'q1'
let q1 = document.querySelector('#q1');

// Select all <p> elements within q1 that have the class 'highlighted'
let ps = q1.querySelectorAll('div.highlighted > p');

Example Exercise

Given the following HTML structure:

html
<div id="test-div">
  <div class="c-red">
    <p id="test-p">JavaScript</p>
    <p>Java</p>
  </div>
  <div class="c-red c-green">
    <p>Python</p>
    <p>Ruby</p>
    <p>Swift</p>
  </div>
  <div class="c-green">
    <p>Scheme</p>
    <p>Haskell</p>
  </div>
</div>

Select the specified nodes:

javascript
// Select <p>JavaScript</p>
let js = document.querySelector('#test-p');

// Select <p>Python</p>, <p>Ruby</p>, <p>Swift</p>
let arr = document.querySelectorAll('.c-red.c-green p');

// Select <p>Haskell</p>
let haskell = document.querySelector('.c-green p:last-child');

// Test cases
if (!js || js.innerText !== 'JavaScript') {
    alert('select javascript failed!');
} else if (!arr || arr.length !== 3 || !arr[0] || !arr[1] || !arr[2] || arr[0].innerText !== 'Python' || arr[1].innerText !== 'Ruby' || arr[2].innerText !== 'Swift') {
    console.log('Failed to select Python, Ruby, Swift!');
} else if (!haskell || haskell.innerText !== 'Haskell') {
    console.log('selecting haskell failed!');
} else {
    console.log('test passed!');
}
Manipulating the DOM has loaded