Shehu-Hikmah

Shehu-Hikmah

Document Object Model (DOM) Essentials With JavaScript

Document Object Model (DOM) Essentials With JavaScript

Subscribe to my newsletter and never miss my upcoming articles

As the usage of internet evolves leading to creation of more webpages and multiple users across deferent interfaces. These changes led to the invention of Dynamic HTML using JavaScript to create interactive webpages (CSS and HTML), albeit this approach was not sustainable due to many constraint putting into consideration of great user experience on the web with different browser vendors. This led to adoption of DOM scripting as a standard by the World Wide Web Consortium (W3C), which has 3 different specifications as core DOM, XML DOM and HTML DOM all aimed at manipulating document and dynamically update contents and styles. We will concentrate on HTML DOM manipulation with JavaScript. The page loaded on the window as a document (HTML DOM) which is rendered in form of a tree structured nodes with each element having specific levels and name through which you can manipulate and alter, change it style, change the content or create new elements as children or siblings or even delete them.

TYPES OF NODES

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<div>
    <p >Example of paragraph</p>
   <p>Example of paragraph</p>

</div>
</body>
</html>

Element node: An element, as it exists in the DOM. Root node: The top node in the tree, which in the case of HTML is always the HTML node. Child node: A node directly inside another node. For example, paragraph is a child of div in the above example. Descendant node: A node anywhere inside another node. For example, paragraph is a child of div in the above example, and it is also a descendant. Paragraph is not a child of BODY, as it is two levels below it in the tree, but it is a descendant of BODY. Parent node: A node which has another node inside it. For example, BODY is the parent node of div in the above example. Sibling nodes: Nodes that sit on the same level in the DOM tree. For example, paragraph 1 and Paragraph 2 are siblings in the above example. Text node: A node containing a text string. used to Access the Document through the DOM.

As JavaScript developer, you are already familiar with writing element to the DOM using document.write(), which adds a string to the document mostly textnode, and it cannot be used to manipulate more complex DOM elements, However, you need a way to reach what you want to change or add content or even delete, this is exactly what the DOM methods provide you with (a sort of Application Programming Interface API). You can access the document through three main methods:

1. document.getElementsByTagName('p')

The getElementsByTagName('p'), the method returns a list of all the elements with the tag name p as objects (where p can be any HTML element). See example below

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Practice DOM</title>
</head>
<h1>Eaxmples of Programin Language</h1>
<p>We have Numerous languages</p>
<h2>Eaxmples</h2>
<ol id="examples">
  <li>JavaScript</li>
  <li>PHP</li>
  <li>Python</li>
  <li>Ruby</li>
  <li>C#</li>
</ol>
<p>some of the above could be used for both front end development</p>
<p>JavaScript is implented in browser</p>
<img src="no.jpg" alt="image">
<img src="no.jpg" alt="image">
<body>

    <script>
        function countElements(){
            var listElements = document.getElementsByTagName('li');
            var paragraphs = document.getElementsByTagName('p');
            var image = document.getElementsByTagName('img');
            var notification = 'There is a total of ' + listElements.length + ' list items\n';
            notification += 'a total of ' + image.length + ' image\n';
            notification += 'and a total ' + paragraphs.length + ' paragraphs.\n Rendered as docuement in the webpage';
            alert(notification); 
        }
window.onload = countElements;
    </script>
</body>
</html>

2. document.getElementById('id')

The getElementById('id'), the method returns to the webpage the element with the ID as an object. See the example below

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 id="heading">This is an Heading</h1>
    <button href="" onclick="changeColor()">changeColor</button>
    <script>
        function changeColor(){
            var headText = document.getElementById("heading");
            headText.style.color ="blue";
        }
    </script>
</body>
</html>

3. document.getElementsByClassName('cssClass')

The getElementsByClassName('cssClass'), the method returns all the elements using that class name.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Practice DOM</title>
</head>
<h1>Eaxmples of Programin Language</h1>
<p class="p1">We have Numerous languages</p>
<h2>Eaxmples</h2>
<ol id="examples">
  <li class="list-prog">JavaScript</li>
  <li class="list-prog">PHP</li>
  <li class="list-prog">Python</li>
  <li class="list-prog">Ruby</li>
  <li class="list-prog">C#</li>
</ol>
<p class="p1">some of the above could be used for both front end development</p>
<p class="p1">JavaScript is implented in browser</p>
<img class="image" src="no.jpg" alt="image">
<img class="image" src="no.jpg" alt="image">
<body>

    <script>
        function countElements(){
            var listElements = document.getElementsByClassName('list-prog');
            var paragraphs = document.getElementsByClassName('p1');
            var image = document.getElementsByClassName('image');
            var notification = 'There is  a total of ' + listElements.length + ' list items\n';
            notification += 'a total of ' + image.length + ' image\n';
            notification += 'and a total ' + paragraphs.length + ' paragraphs.\n Rendered as docuement in the webpage';
            alert(notification); 
        }
window.onload = countElements;
    </script>
</body>
</html>

IMPORTANT DOM METHODS

The followings are essential DOM manipulation methods

Methods for Creating New Nodes

The document.createElement(element): –this method creates a new element node with the name element. You provide the element name as a string.

var sampleElement = document.createElement("p");

The document.createTextNode(string):–this method creates a new text node with the node value of string

var textnodeExample = document.createTextNode("Food for thought");

The newNode =node.cloneNode(item):–this method creates newNode as a copy (clone) of node. If the item is true the clone includes clones of all the child nodes of the original.

var itemToClone = itemTobeClone.cloneNode(true);

The node.appendChild(newNode):-this method adds newNode as a new (last) child node to node.

document.body.appendChild(sampleElement);

The node.insertBefore(newNode,oldNode):–this method inserts newNode as a new child node of node before oldNode

SampleNode.insertBefore(sampleElement, SampleNode.childNodes[0]);

The node.removeChild(oldNode): –this method removes the child oldNode from node.

SampleNode.removeChild(SampleNode.childNodes[0]);

The node.replaceChild(newNode, oldNode): – this method replaces the child node oldNode of node with newNode.

SampleNode.replaceChild(textnode, SampleNode.childNodes[0]);

The element.innerHTML: –this method reads or writes the HTML content of the given element as a string – including all child nodes with their attributes and text content.

document.getElementById("p1").innerHTML = "Changed Text!";

The insertAdjacentElement():- this method inserts a the specified element into a specified position. It has four positioning values which includes "afterbegin" to insert an element in an adjacent value position as the first child of an element on the node tree, "afterend" to insert an element in an adjacent value position after an element on the node tree, "beforebegin" to insert an element in an adjacent value position before the element it serves as child to on the node tree, "beforeend" to insert an element in an adjacent value position after the element it serves as child to on the node tree.

var sample = document.getElementById("id");
 sample.insertAdjacentElement("afterend", sample);

Methods for Reading element attributes, node values and other node data

The node.getAttribute(‘attribute’):–this method retrieves the value of attribute with the name attribute either class or it.

var sample = document.getElementsByTagName("p").getAttribute("class");

The node.setAttribute(‘attribute’, 'value'):–this method sets the value of the attribute with the name attribute to value.

document.getElementsByTagName("p").setAttribute("class", "p1");

The node.nodeType: –this method reads the type of the node (1 = element, 3 = text node). If the node is an element node, the nodeType property will return 1. If the node is an attribute node, the nodeType property will return 2. If the node is a text node, the nodeType property will return 3. If the node is a comment node, the nodeType property will return 8.

document.getElementById("p1").nodeType;

The node.nodeName: –this method reads the name of the node.

var sample = document.getElementById("p1").nodeName

The node.nodeValue:–this method reads or sets the value of the node (the text content in the case of text nodes)

Methods for Navigating between nodes

The node.previousSibling: –this method retrieves the previous sibling node and stores it as an object.

var element = document.getElementById("sample").previousSibling.innerHTML

The node.nextSibling: –this method retrieves the next sibling node and stores it as an object.

var element = document.getElementById("sample").nextSibling.innerHTML;

The node.childNodes: –this method retrieves all child nodes of the object and stores them in an list. There are shortcuts for the first and last child node, named node.firstChild and node.lastChild.

var sample = document.body.childNodes;

The node.parentNode: –this method retrieves the node containing node.

var sample = document.getElementById("p1").parentNode.nodeName;

You can read more from W3C school website for more methods

 
Share this