Tallaght Campus

Department of Computing

Javascript DOM Tree Manipulation
  1. DOM Tree

    DOM Tree

    In the tutorial we will be working with this example file. Open it in a browser and have a look at the source HTML.

    The elements of the page are represented by objects in the Javascript DOM API and these are shown in the figure labelled DOM objects below.

    The same structure can be modelled as a tree. The figure labelled Tree with child elements contains this representation of the objects.

    The DOM provides another view of the document, which includes objects to represent the textual fragments between HTML elements and the textual content of HTML elements. The object tree of this view of the page is shown in the figure labelled Tree with child nodes.

  2. Exploring the DOM tree

    Exploring the DOM trees

    • As seen above, there are two different trees of objects.
    • One (Tree with child elements) is a subset of the other (Tree with child nodes).
    • The 'glue' that constructs the trees is in object properties children and childNodes.

    Tree with child nodes

    'Glue' property: childNodes

    This tree consists of objects of type Node. There are many subtypes of Node but the ones of interest here are

    • Document (this is the type of the object document)
    • Element (this is the subtype representing HTML elements)
    • Text (this is the subtype representing textual fragments in the document)

    Each DOM object of type Node has the property childNodes, which stores the collection of child nodes for the node. In this way the tree of nodes is constructed.

    Tree with child elements

    'Glue' property: children

    This tree consists of objects of type Element. It is a subtree of the tree containing Node objects.

    Each DOM object of type Element (representing a HTML element) has the property children, which stores the collection of child HTML elements for the element. In this way the tree of HTML element objects is constructed. It is a sub-tree of the tree of nodes.

    Expressions for accessing objects in the tree

    We can use children and childNodes properties to access children of any object.

    With the example page loaded in the browser, open the console in the developer tools and write expressions for the objects representing the following elements:

    • the body element
      document.children[0].children[1]
      or with the shortcut available only for the body element:
      document.body
    • the article element
      document.body.children[0]
    • the second list item
      document.body.children[0].children[3].children[1]
    • the textual fragment between the ol open tag and the first li open tag
      document.body.children[0].children[3].childNodes[0]
    • the text contained in the h1 heading
      document.body.children[0].children[1].childNodes[0]
    • the text preceding the break in the aside element
      document.body.children[0].children[0].childNodes[0]
  3. Creating elements and nodes

    Creating elements and text nodes

    There are methods on the document object for creating various types of nodes. We are interested in types Element and Text.

    • To create an element object (one of type Element) use method createElement, passing in the tag name:
      let newParagraphElement = document.createElement('h2');
    • To create a text node object (one of type Text) use method createTextNode, passing in a string containing the text:
      let newTextNode = document.createTextNode("Hello");
  4. Inserting, deleting and replacing child nodes

    Inserting, deleting and replacing child nodes

    We will learn how to modify the DOM object tree through the Node interface. The Node interface has many methods for manipulating the tree but we will be using only some of them.

    To work with the example file, open it in a browser and open the console in the developer tools.

    Appending a child node

    Let's add a paragraph at the end of the page by creating an Element object and adding it as a child of the article.

    // create the element object
    let newP = document.createElement('p');
    
    // create the text node object
    let newTxt = document.createTextNode("This ends the article.");
    
    // add the text node object as the last child of the new paragraph object
    newP.appendChild(newTxt);
    
    // add the paragraph element object as the last child of the article
    document.body.children[0].appendChild(newP);

    Removing a child node

    Now let's remove the first list item ("The world is listening").

    // access the element we want to remove
    let elementToRemove = document.body.children[0].children[3].children[0];
    
    // parent of the element to remove
    let parent = elementToRemove.parentElement;
    
    // remove the element
    parent.removeChild(elementToRemove);

    Inserting a child node

    We insert a node before a sibling. For example, let's insert a new list item just before the second one.

    // access the element in front of which we want to insert the new one
    let secondListItem = document.body.children[0].children[3].children[1];
    
    // create a new list item element
    let newLI = document.createElement('li');
    
    // rather than creating and adding a text node,
    //we can set the innerText property on the element
    newLI.innerText = "It is important to be inclusive";
    
    // insert the node, by calling insertBefore() on the parent element
    secondListItem.parentElement.insertBefore(newLI, secondListItem);

    Replacing a child node

    Let's replace the last paragraph with another one.

    // create the new paragraph
    let newEndingParagraph = document.createElement('p');
    newEndingParagraph.appendChild(document.createTextNode('We hope you liked this article.'));
    
    // access the article element
    let article = document.body.children[0];
    
    // access the last element in the article
    let indexOfLastArticleElement = article.children.length - 1;
    let lastArticleElement = article.children[indexOfLastArticleElement];
    
    // replace the old paragraph with the new one
    article.replaceChild(newEndingParagraph, lastArticleElement);
  5. Bringing it all together

    Bringing it all together

    Now we will make the changes to the article from a function and set it as handler for an event.

    • Open the example page in a browser and click the Save as menu item to save it as an HTML file called example.html. Open the HTML file in VS Code.
    • In VS Code create a Javascript file called example.js and include it in the HTML file using a script element.
    • Write a function in the Javascript file that performs all the actions presented in the previous section.
    • Using Javascript code, set the function as handler for any keystroke.

    Download completed exercise