Document Object Model (DOM)

Junghoo Cho

cho@cs.ucla.edu

HTML DOM (Document Object Model)

Adding JavaScript to a Web page

Document to DOM Tree

Three key node types

  1. Element node: An HTML element
  2. Text node: Text enclosed in an element
  3. Attribute node: Attribute of an element

DOM Conversion Example

<!DOCTYPE html>
<html>
<head><title>Page Title</title></head>
<body>
    <h1>Heading</h1>
    <a href="good/">Link</a>
</body>
</html>

DOM Tree in JavaScript

DOM Object Properties

Accessing DOM Node

  1. Traverse the tree using the childNodes property starting from document
  2. Get node(s) directly
    document.getElementByID('id');
    document.getElementsByTagName('h1');
    document.getElementsByClassName('class');
    document.querySelectorAll('body > a')
    

Manipulating DOM Nodes

DOM Manipulation Example (1)

document.body.style.background = "yellow";   
document.getElementById('warning1').style.color = "red"; 
document.body.innerHTML = "<p>new text</p>"; 

DOM Manipulation Example (2)

let newP = document.createElement("p");
let newText = document.createTextNode("new text");
newP.appendChild(newText); 
document.body.replaceChild(newP);

DOM Manipulation Example (3)

document.getElementById('myform1').reset();
document.getElementById('myform1').submit();

Event-Driven Programming

Event Handling in JavaScript

Setting Event Handler

  1. In JavaScript: obj.addEventListener(event, handler)
    function ChangeColor(event) {
        document.body.style.color = "red";
    }
    document.body.addEventListener("click", ChangeColor);
    
  2. In HTML: onevent="stmt;" attribute:
    <body onclick="ChangeColor();">             
    

Our Demo Code

<html>
<meta charset="utf-8">
<head><title>JavaScript Example</title></head>
<body>Click on this document!</body>
<script>
    let colors = [ "yellow", "blue", "red" ];
    let i=0;
    function ChangeColor(event) { 
        document.body.style.backgroundColor = colors[i++%3]; 
    }
    document.body.addEventListener("click", ChangeColor);
</script>
</html>

References