Skip to content

M04 - DOM, Document Object Model

Web browser as a programming environment

Browser has a DOM (Document Object Model) and BOM (Browser Object Model) which are accessible from JavaScript programming. Window object is top most object which uses BOM to define web browser window and its properties. DOM is used to get connection to loaded HTML document.

Image 01

BOM

BOM will give for example location and navigator objects. location object are used to detect used URL or redirect browser to new address. navigator object can be used to detect browser version etc. You can use functions to open/close windows, alerts, prompts, etc. These objects aren't so important in this course.

DOM

DOM is a programming interface to modify loaded HTML/CSS document from JavaScript. DOM will describe loaded document as an objects. Every element is a node in DOM. Developer can use different functions to find element from DOM, like firstChild, lastChild, childNodes, parentNodes or using different functions like document.getElementById() or document.getElementsByTagName().

Note

DOM descripes whole HTML document as a DOM tree, which has a nodes.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE HTML>
<html>
<head>
  <title>Web Programming</title>
</head>
<body>
  <h1>Web Programming</h1>
  <ul>
    <li>First thing</li>
    <li>Second thing</li>
  </ul>
</body>
</html>

You can use for example http://software.hixie.ch/utilities/js/live-dom-viewer/# service to see DOM nodes.

Image 02

Above HTML has (for example):

  • HTML node has three child: HEAD, #text ja BODY. (#text is newline character after HEAD)
  • UL node is parent for both LI nodes
  • text, li, text, li and text are siblings

Finding elements from DOM

Basicly you are using a following functions:

getElementById function returns an element with a specified value with id (only one).

Example: Find a demo node and change text and text color to blue.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html>
<body>
  <p id="demo">Some text in here!</p>

  <script>
    let elem = document.getElementById("demo");
    elem.innerHTML   = "Blue text!";
    elem.style.color = "blue";
  </script>

</body>
</html>

getElementsByName function returns a collection of elements with a specified name.

Example: Find all elements by name

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<body>
  <p>First Name: <input name="fname" type="text" value="Michael"></p>
  <p>First Name: <input name="fname" type="text" value="Doug"></p>

  <p>The tag name of the first element with the name "fname" is:</p>
  <p id="demo"></p>

  <script>
    let elements = document.getElementsByName("fname");
    document.getElementById("demo").innerHTML = elements[0].tagName;
  </script>
</body>
</html>

getElementsByTagName function returns a collection of all elements with a specified tag name.

Example: Find elements by tag name

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<body>
  <p>An unordered list:</p>
  <ul>
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
  </ul>

  <p>The innerHTML of the second li element is:</p>
  <p id="demo"></p>

  <script>
    const collection = document.getElementsByTagName("li");
    document.getElementById("demo").innerHTML = collection[1].innerHTML;
  </script>
</body>
</html>

getElementsByClassName function returns a collection of elements with a specified class name(s).

Example: change target text

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE html>
<html>
<body>
  <p>Change the text of the first element with class="example":</p>

  <div class="example">Element1</div>
  <div class="example">Element2</div>

  <script>
    const collection = document.getElementsByClassName("example");
    collection[0].innerHTML = "Hello World!";
  </script>
</body>
</html>

querySelector function returns the first element that matches a CSS selector.

Example: Find a first class which has value sini and change background color to blue.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<body>

  <h2>Header</h2>
  <p>Para 1</p>
  <p class="sini">Para 2</p> <!-- only this will change to blue -->
  <p class="sini">Para 3</p>

  <script>
    document.querySelector("p.sini").style.backgroundColor = "blue";
  </script>

</body>
</html>

querySelectorAll function returns all elements that matches a CSS selector(s).

Example: Change paragraph background color to blue if it has a class=sini attribute.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<body>

  <h2>Header</h2>
  <p>Para 1</p>
  <p class="sini">Para 2</p> <!-- blue background -->
  <p class="sini">Para 3</p> <!-- blue background -->

  <script>
    let elements = document.querySelectorAll("p.sini");
    for (let i = 0; i < elements.length; i++) {
      elements[i].style.backgroundColor = "blue";
    } 
  </script>

</body>
</html>

Adding elements or content

You can use for example a following methods to modify elements:

  • document.createElement add a new element
  • document.createTextNode add a new text node
  • element.appendChild adding a element to some element (last)

A few examples

  1. Adding a new li element to unordered list.
    1
    2
    3
    4
    <ul id="demolist">
      <li>First</li>
      <li>Second</li>
    </ul>
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    // find a node
    let ulnode = document.getElementById("demolist");
    // create a new node
    let linode = document.createElement('li');
    // create a new text node == text
    let litext = document.createTextNode('Third');
    // append text node to li element
    linode.appendChild(litext);
    // append li element to ul element
    ulnode.appendChild(linode);
    
    Will modify DOM:
    1
    2
    3
    4
    5
    <ul id="demolist">
      <li>First</li>
      <li>Second</li>
      <li>Third</li>
    </ul>
    

Note

There are quite a many different functions which you can use to modify DOM like insertBefore, insertAfter, append, append, append, after etc... you will learn more later in exercises.

Remove elements

You can use remove() function to remove node and parentElem.removeChild() function to remove child element.

Example - Remove clicked li element from ul list.

1
2
3
4
5
<ul id="demolist">
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
</ul>
1
2
3
4
5
6
7
8
<script>
  const collection = document.getElementsByTagName("li");
  for(let element of collection) {
    element.onclick = function() {
      element.remove();
    }
  }
</script>

Example - Remove all li elements from ul list.

1
2
3
4
5
<ul id="demolist">
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
</ul>
1
2
3
4
5
6
7
8
<script>
// find ul list
let list = document.getElementById("demolist");
// if list has child nodes -> remove first one
while (list.hasChildNodes()) {
  list.removeChild(list.firstChild);
}
</script>

HTML DOM Events

DOM nodes will generate different events. Here are a common list of events:

  • click mouse click inside some DOM element/node
  • mouseover, mouseout, mousedown, mouseup, mousemove, contextmenu mouse events
  • submit, focus form and it fields events
  • keydown, keyup events from keyboard

Developer can use a few different ways to implement event handling to application.

  • as a HTML attribute onclick="..."
  • as a DOM property elem.onclick = function...
  • as a Event listener elem.addEventListener(event, handler[, phase])

A few examples

  1. Add event handling with HTML attribute

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    <!-- all javascript code inline -->
    <button onclick="alert('You clicked me!')">Klikkaa</button>
    
    <!-- call own made function-->
    <p onclick="functionCallHere('You clicked me!')">Klikkaa</p>
    <script>
      function functionCallHere(text) {  
        alert(text);
      }
    </script>
    

  2. Event handing with DOM property

    1
    <button id="btn1">Klikkaa</button>
    
    1
    2
    3
    4
    5
    <script>
    btn1.onclick = function() {
      alert('You clicked me!');
    }
    </script>
    

  3. Event handling with event listeners.

    1
    <p id="elem">mouseover/mouseout/click?</p>
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    <script>
    function fn1() {
      elem.style.backgroundColor = "yellow";
    }
    
    function fn2() {
      elem.style.backgroundColor = "white";
    }
    
    function fn3() {
      alert('You clicked me!');
    };
    
    elem.addEventListener("mouseover", fn1); // background yellow
    elem.addEventListener("mouseout", fn2);  // background white
    elem.addEventListener("click", fn3);     // alert
    </script>
    

  4. this keywork with events

    1
    <p onclick="fn(this)">Click me?</p>
    
    1
    2
    3
    4
    5
    <script>
    function fn(elem) {
      elem.innerHTML = "You clicked me!";
    }
    </script>
    

  • Usually developer need more information about event content (where clicked etc..)
  • Developer can find more detailed information inside a event object (like [event.screenX, event.screenY] or [event.keyCode])
  1. More details from event - handleEvent method will be called automatically.
    1
    <p id="elem">Click and hold mouse button down</p>
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Selection {
      handleEvent(event) {
        switch(event.type) {
          case 'mousedown':
            elem.style.backgroundColor = "yellow";
            elem.innerHTML = "mouse down X:"
                          + event.screenX + "Y: " + event.screenY;
            break;
          case 'mouseup':
            elem.style.backgroundColor = "white";
            elem.innerHTML = "Click and hold mouse button down";
            break;
        }
      }
    }
    let selection = new Selection();
    elem.addEventListener('mousedown', selection);
    elem.addEventListener('mouseup', selection);
    

Note

You can find a list of HTML Events here - HTML DOM Events

HTML form and events

  • HTML form and fields has a lot of different propeties and events
  • Developer can find a specific form using a following commands: document.getElementById('formId'), document.forms.formId or document.forms[1] which uses a form appearance number.
  • Form elements can be found using a form.elements.fieldId, form.fieldId or form.elements[1]
  • Form field properties can be used normally like input.value, select.value, textarea.value, input.checked or select.selectedIndex, etc...

A few examples

  1. Detect which checkbox is checked

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    <form>
      <input type="checkbox" name="number" value="12"> 12<br>
      <input type="checkbox" name="number" value="20"> 20<br>
      <input type="checkbox" name="number" value="53"> 53</br>
      <button id="btn">Click me!</button>
    </form>
    <script>
      function fn() {
        let form = document.forms[0]; // first and only form
        let numbers = form.elements.number; // All number elements
        if (numbers[2].checked) { // third number is checked
          // show alert with third value
          alert(numbers[2].value + " checked!"); 
        } 
      };
      btn.addEventListener("click", fn);
    </script>
    

  2. Read value from form component and show in div.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    <form id="form">
       <input type="text" id="number"><br>
       <button type="button" onclick="showNumber(form.number.value)">
         Show a number
       </button>
    </form>
    <div id="result"></div>
    <script>   
      function showNumber(a) {  
        var div = document.getElementById("result");
        div.innerHTML = "Number is " + a + "<br>";
      } 
    </script>
    

  3. Small example with select

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <select id="selection">
      <option value="Select euros, Please!">Select euros</option>
      <option value="13">13 euros</option>
      <option value="31">31 euros</option>
    </select>
    <button onclick="show()">
      Show selection
    </button>
    <div id="result"></div>
    <script>
      function show() {  
       var div = document.getElementById("result");
       div.innerHTML = selection.value; // selected value
       if (selection.selectedIndex == 1) { // second option is  "selected"
          console.log("Wau you selected 13eur!");
       }
       selection.options[0].selected = true; // change first one to "selected"
    } 
    </script>