JavaScript DOM Nodes

DOM - Nodes

Node :

There is one more kind of manipulation that can be achieved on the DOM tree. We can dynamically add or remove HTML elements. Also, we can access and modify the elements by referring to the relationship of the target HTML element with the element that we already have access to.

According to W3C DOM standard, each HTML element can be referred to as a Node. For example, the entire html document is a 'document node', every other element inside HTML is 'element node'. The content inside these HTML elements is a 'text node'.

dom htmlcode
dom structure

Let us see how the Node relationship helps us in Node manipulation.

Node Relationship :

These nodes appear in hierarchical structure inside the browser. And this hierarchical relationship between the nodes allows us to traverse through the DOM tree.

  • Top node is called the root. It does not have any parent.
  • Every other node in the tree belongs to one parent
  • Every node may have number of children
  • Node with same parent are referred as siblings.
JS DOM

Let us see DOM API properties that allow us to navigate this tree of nodes:

Property Description
parentNode Returns Node object that is parent node of specified node. We can only retrieve this property and cannot set it. Example: HTML DOM: JS CODE: document.body.parentNode //Returns Node onject
childNodes Returns NodeList object, i.e collection of child nodes of specified node. Each child can be accessed by index number that refers to it‘s position inside parent element. First position is at index ‘0’ Example: HTML DOM:

JS CODE: document.body.childNodes //Returns NodeList object consisting of nodes: h1 and p
firstChild Returns Node object which is first child of specified node. Its is equivalent to childNodes[0]. Example: HTML DOM:

JS Code: document.getElementById("div1").firstChild; //Returns h1 element
lastChild Returns Node object which is last child of specified node. Example: HTML DOM:

JS Code: document.getElementById("div1").lastChild; //Returns p element
nextSibling Returns Node object of node that immediately follows specified node at same tree level Example: HTML DOM:

JS Code: document.getElementById("heading1").nextSibling; //Returns p element
previousSibling Returns Node object of node that previous node of specified node at the same tree level. Example: HTML DOM:

JS Code: document.getElementById("para1").previousSibling; //Returns h1 element

Similar to all these properties of Node object we also have properties - parentElement, firstElementChild, lastElementChild, nextElementSibling, previousElementSibling.

The difference is that Element properties return only the Element object whereas Node properties return element, text and attribute nodes with respect to the specified Node. Also, whitespaces are considered as '#text' node by the Node properties.

Node Manipulation :

The node relationship also allows us to modify the tree of nodes by adding new nodes and removing the existing nodes, if required. Let us explore these methods:

For the given HTML page, below methods will do the following:

  • Create a new element
  • Create new content
  • Add new content to the new element
  • Add a new element to the existing DOM tree
DOM Node Manipulation

Demo :

CODE/PROGRAM/EXAMPLE
<!DOCTYPE html>
<html>
  <head>
    <script>
      //Requirement 1: Adding all the food items to cart
      function Add_all() {
        var from = document.getElementById("from");
        var cln = from.cloneNode(true);
        document.getElementById("to").appendChild(cln);
        //document.getElementById(‘heading’).style.visibility = ‘hidden’;
        var x = document.getElementById("Add_all");
        x.disabled = "true";
        x.style.background = "burlywood";
        x.style.fontWeight = "bold";
      }
      //Requirement 2: Removing all the food items from the cart
      function Remove_all() {
        var to = document.getElementById("to");
        if (to.hasChildNodes()) {
          to.removeChild(to.childNodes[0]);
        } else alert("No child node found !! ");
        var x = document.getElementById("Remove_all");
        x.disabled = "true";
        x.style.background = "burlywood";
        x.style.fontWeight = "bold";
      }

      //Requirement 4: Removing one by one the food items to cart
      function Remove_one() {
        var count1 = 0;
        var images = document.getElementById("to").getElementsByTagName("img");
        var x = images.length;
        if (count1 < x) {
          count1++;
          var node = document.getElementById("to").lastChild;
          document.getElementById("from").appendChild(node);
          //document.getElementById(‘to’).removeChild(node);
          var x = document.getElementById("Remove_one");
          //x.disabled = ‘true’;
          x.style.background = "burlywood";
          x.style.fontWeight = "bold";
          console.log(count1);
        }
      }

      //Requirement 3: Adding one by one the food items to cart
      function Add_one() {
        var count = 0;
        var images = document
          .getElementById("from")
          .getElementsByTagName("img");
        var x = images.length;
        if (count < x) {
          count++;
          var img = document.getElementById("myImg");
          //var clnImg = img.cloneNode(true);
          document.getElementById("to").appendChild(img);
          var x = document.getElementById("Add_one");
          //x.disabled = ‘true’;
          x.style.background = "burlywood";
          x.style.fontWeight = "bold";
          console.log(count);
        }
      }
    </script>
    <style>
      #from {
        float: left;
        width: 200px;
        height: 550px;
      }
      #buttons {
        width: 150px;
        height: 550px;
        display: block;
      }
      #to {
        width: 200px;
        height: 550px;
        float: right;
      }
      input[type="button"] {
        border-radius: 10px;
        padding: 10px;
        margin: 28.5px;
        font-size: 15px;
        width: 120px;
        height: 50px;
      }
      body {
        background-image: url("../images/javascript-images/BT.png" width="1157" style="width:100%; heigth: auto; max-width:1157");
        background-repeat: no-repeat;
      }
      #main-head {
        color: blue;
      }
      #outer {
        height: 550;
        width: 900px;
        box-shadow: 5px 5px 5px grey;
        background-color: white;
      }
      #outer1 {
        height: 50;
        width: 900px;
        box-shadow: 2px 2px 2px grey;
        background-color: white;
      }
    </style>
  </head>

  <body>
    <center>
      <div id="outer1">
        <h1 id="main-head">Place Your Order</h1>
      </div>
      <div id="outer">
        <div id="from" style="background-color:white">
          <div id="myImg">
            <h5>Chinese Platter</h5>
            <img src="images\chinesefood.jpg" width="1157" style="width:100%; heigth: auto; max-width:1157" height="100px" width="150px" />
          </div>
          <div id="myImg">
            <h5>Veg Burger</h5>
            <img src="images\grilledveg.jpg" width="1157" style="width:100%; heigth: auto; max-width:1157" height="100px" width="150px" />
          </div>
          <div id="myImg">
            <h5>Cheese Pizza</h5>
            <img src="images\pizza.jpg" width="1157" style="width:100%; heigth: auto; max-width:1157" height="100px" width="150px" />
          </div>
        </div>
        <div id="to" style="background-color:white"></div>
        <div id="buttons" style="background-color:white">
          <input
            type="button"
            value="Add All"
            title="Add them all !!"
            id="Add_all"
            onclick="Add_all()"
          />
          <br /><br />
          <input
            type="button"
            value="Add One"
            title="Add them one by one !!"
            id="Add_one"
            onclick="Add_one()"
          />
          <br /><br />
          <input
            type="button"
            value="Remove All"
            title="Remove them all!!"
            id="Remove_all"
            onclick="Remove_all()"
          />
          <br /><br />
          <input
            type="button"
            value="Remove One"
            title="Remove them one by one!!"
            id="Remove_one"
            onclick="Remove_one()"
          />
          <br /><br />
        </div>
      </div>
    </center>
  </body>
</html>
#javascript_node #Nodes_in_javascript #node_js #npm_js #node_js_examples

(New page will open, for Comment)

Not yet commented...