JavaScript : DOM

JavaScript : DOM

·

6 min read

What is DOM?

DOM or Document Object Model is a programming interface for HTML documents. It includes all the HTML tags, attributes and text in between tags. It enables scripts to access and modify a document's content, structure, and style.

The Window Object is the top-level object in the browser. Document Object is part of window Object, using which we can access any DOM element.

console.log(window);
console.log(window.document);
//We can access any DOM Elements now
console.log(document.head); //Accessing Head of a HTML document
console.log(document.body); //Accessing Body of a HTML document
console.log(document.links); //Accessing links if any of a HTML document
//We can also store it in a variable
const head=document.head;
console.log(head);
//It is not mandatory to write window object while accessing dom element

Besides Accessing, we can also modify DOM elements

document.body.innerHTML='<p>innerHTML property is used to replace the HTML within an element</p>';

//Modifying CSS properties
document.body.style.color='red';
//CSS Properties having hyphen are replaced with camelCasing
document.body.style.backgroundColor='yellow';

Selecting Elements-

  1. getElementById()

    It is used to select elements having a particular ID, if no element with such id is present in the HTML document, it returns null.

     <html>
         <head>
             <title>getElementById Example</title>
         </head>
         <body>
             <h1 id='heading'>This is an Example</h1>
         </body>
     </html>
    
     const element=document.getElementById('heading'); // h1 tag with id heading is selected
    
     //Modifying the Element
     element.style.color='white';
     element.style.backgroundColor='black';
     element.style.padding='10px';
    
  2. getElementsByClassName()

    it is used to get HTMLCollection(Array) of elements having a particular class name.

     <nav>
       <ul>
            <li class="nav-item">Home</li>
            <li class="nav-item">About</li>
            <li class="nav-item">Contact Us</li>
       </ul>
     </nav>
    
     const item=document.getElementsByClassName('nav-items');
     console.log(item);
     //The output is- ['Home', 'About', 'Contact Us']
    
  3. querySelector()

    It is used to select the first element in the document having same CSS selector, i.e a node(HTMLtags), class or an id.

     <html>
         <head>
             <title>QuerySelector Example</title>
         </head>
         <body>
             <h1 id='heading'>First</h1>
             <h1 id='heading'>Second</h1>
             <h1 id='heading'>Third</h1>
         </body>
     </html>
    
     document.querySelector('h1');
     //<h1 id='heading'>First</h1> is selected
    
  4. querySelectorAll()

    it is used to get NodeLisrt(Array) of elements having a CSS selector. It can also be used in pseudo-classes(: hover etc)

     <html>
         <head>
             <title>querySelectorAll Example</title>
         </head>
         <body>
             <li class="items">First Text</li>
             <li class="items">Second Text</li>
             <li class="items">Third Text</li>
             <li class="items">Fourth Text</li>
             <li class="items">Fifth Text</li>
         </body>
     </html>
    
     const item=document.querySelectorAll('.items');
     //All the li nodes are selected in a NodeList
     //We can modify the Nodes
     item[0].innerText='Modification of First Text';
    
     //It can also be modified using forEach method
     item.forEach(i,index){
         if((index+1)%2!=0)
             i.style.backgroundColor='red';
         else
             i.style.backgroundColor='blue';
     }
     //Here we changed the color to red at odd indexes and blue at even indexes
    
Note
forEach is not a function for HTMLCollection, so it doesn't work on .getElementsByClassName, in that case, the HTMLCollection can be Array Ex- const newArray=Array.from(item);

Traversing In DOM

  1. Child Node to Parent Node

    To access the parent Node of a specified Node we use the parentNode property.

     <div class="parent">
         <div class="child">First</div>
         <div class="child">Second</div>
         <div class="child">Third</div>
         <div class="child">Fourth</div>
     </div>
    
     const child=document.querySelector('.child'); //First child get selected
     const parent=child.parentNode; //returnsthe parent Node
     //In case there is no parent Node the property returns null
    
     //Modifying Parent Node
     parent.style.backgroundColor='grey';
     parent.style.color='red';
    
  2. Parent Node to Child Nodes

    • To get all Children:

      childNodes property return a NodeList(Array) of all child nodes of specific node

        const parent=document.querySelector('.parent');
        const children=parent.childNodes;
        console.log(children); // Display a NodeList of all child Nodes
        //A particular child can be accessed sames as in array
        children[0].innerText='Modified Text';
      
    • To get First Child:

      We use the firstChild property to access the very first child node of a specific node

        const parent=document.querySelector('.parent');
        const first= parent.firstChild;
        // It Returns null if the node has no child
        console.log(first);
      
    • To get Last Child:

      We use the lastChild property to access the very Last child node of a specific node.

        const parent=document.querySelector('.parent');
        const last= parent.LastChild;
        // It Returns null if the node has no child
        console.log(last);
      
  3. Node To Sibling Node

  • To get the next Node:

    We use the nextSibling property to access the next Sibling node of a specified Node.

  • To get the previous Node:

    We use previouSibling property to access the next Sibling node of a specified Node.

const child=document.querySelector('.child:nth-child(2)'); //Selecting the 2nd Child
console.log(child.nextSibling); 
console.log(child.previousSibling);

Creating Element

We use createElement() function to create a Node with element type, which accepts an HTML tag.

The attributes of an element can be set by using setAttribute('x','y') where x is a type of attribute and y is the name of the attribute.

To add text to the new element, we set up a text node using createTextNode() function and append it to the new element using appendChild() function

<div class="parent">
    <div class="child">First</div>
    <div class="child">Second</div>
    <div class="child">Third</div>
    <div class="child">Fourth</div>
</div>
const element=document.createElement('div');
element.setAttribute('class','child'); // adding attribute to the element

//Adding text
const text=document.createTextNode('Test');
element.appendChild(text);

//appening it to the parent node
document.querySelector('.parent').appendChild(element);

Inserting Elements

Now as we can select and create an element, we can easily insert an element in the DOM. As we already know we can insert an element using appendChild() function, but there is another method that provides more flexibility.

In a second way***, the insertAdjacentElement()*** function is called on the element we wish to place before or after, then the position of the new element is passed as an argument. Ex- element.insertAdjacentElement('position',newElement);

There Are total 4 positions where we can add an element-

beforebegin,afterbegin,beforeend,afterend

<!-- STRUCTURE-->

<!-- beforebegin -->
<p class='element'>
  <!-- afterbegin -->
  <!--  ORIGINAL CODE  -->
  <!-- beforeend -->
</p>
<!-- afterend -->

Let us insert an element to DOM now-

<div class="parent">
    <div class="child">First</div>
    <div class="child">Second</div>
    <div class="child">Third</div>
    <div class="child">Fourth</div>
</div>
const parent=document.querySelector('.parent');
const element=document.createElement('div'); //creating an element
element.setAttribute('class','child'); // adding attribute to the element

//Adding text
const text=document.createTextNode('insertElement');//creating text node
element.appendChild(text); //inserting text node to the element

//Inserting element to DOM
parent.insertAdjacentElement('afterbegin',element);
//Now the new element is inserted at the begining of the parent class div
//Similarly beforeend is used to insert element before the end of the selected element

Similarly insertAdjacentText() & insertAdjacentHTML() is used to add custom text and custom HTML respectively.

Also, insertBefore() function is used to insert an element before a reference element, it is called on the Parent Element.

//Inserting Text
function textInsert(){
    const item=document.querySelector('.parent:first-child');
    const text=document.createTextNode(' Child'); //Creating Text Node
    item.insertAdjacentText('beforeend',text); //Inserting Text Node
}

//Inserting HTML
function htmlInsert(){
    const item=document.querySelector('.parent');
    item.insertAdjacentElement('beforeend',`<div class="child">Fifth</div>`);
    //Inserting 5th DIV HTML to the parent class
    //Note ``(back ticks) are used to write html in js file
}

//Inserting Before
function insertingBefore(){
    const third=document.querySelector('.parent:nth-child(3)'); 

    //creating a new element
    const element=document.createElement('div');
    element.setAttribute('class','child'); 
    const text=document.createTextNode('BEFORE THIRD');
    element.appendChild(text);

    //inserting new element before the third item in parent class
    third.insertBefore('element','third');
}

Removing Element

The remove() function is used to remove elements from DOM, it's really simple to remove an element than insert one.

const third=document.querySelector('.parent:nth-child(3)'); 
//Removing the third div from the parent class
third.remove();

Conclusion

This is just a basic use of DOM, but I hope it gives you an idea of what it is, how we can access web page elements with it, and how we can manipulate the contents.

So, the next time you're working with the DOM tree, Think of it as a family tree, with Dom Toretto as the leader and you as a valuable member of the team. With the right knowledge and guidance, you too can manipulate the DOM tree like a member of the Toretto family. Who knows, maybe one day you'll be drifting down the DOM tree like Dom drifts through the streets of LA!