All about DOM and DOM manipulation....

All about DOM and DOM manipulation....

What is DOM and DOM manipulation?

The DOM stands for document object model which is an Application programming interface(API) it is a well-organised representation of HTML Document, where Javascript interact with DOM and access the HTML elements and styles to manipulate them i.e DOM manipulation, So the DOM is basically a connection point between Javascript and HTML elements. As soon as the HTML page loads, DOM is created by the browser and it stores the HTML in atree structure.

The DOM Methods and properties such as document.querySelector() which are used for DOM Manipulation are not the part of javascript instead they are part of something called web APIs which are implemented by the browser, the javascript code interacts with web APIs. There are more web APIs besides DOM such as timers, fetch API and many more.

NOTE: Every web browser uses DOM to make web pages accessible via javaScript

DOM TREE.jpg

As we can see, the tree always starts with the Document object and this is a special object that we have access to in javascript. This object is basically an entry point into the DOM by using commands like-

     document.querySelector();

If one has to select an element from DOM then have to use commands like -

  • document.getElementById(element_ID);
  • document.getElementsByClassName(element_classnames);
  • document.getElementsByName(element_name);
  • document.getElementsByTagName(Tag_name);
  • document.querySelector(selectors) or document.querySelectorAll(selectors);

by using the above-given methods we can select every element in HTML through javascript. Let's see each of the methods one by one-

Get HTML element by Id

Elements of the HTML can be accessed using id, for this user has to add an Id to the particular element you want to access. It returns the object with a particular id, if the element with the desired id is not present in the HTML then it will simply return the null value.

Syntax used:

     document.getElementById(element_ID);

Example: Using get HTML element by Id

 </head>
<body>

    <p id="paragraph">hello world</p>


     // Javascript inside HTML


     <script>
    //   the get element by Id method.

    const paragraphContent=document.getElementById('paragraph');

    console.log(paragraphContent);
    //output: <p id="paragraph"> hello world </p>

    console.log(paragraphContent.textContent);
    //output: hello world


    </script>
</body>
</html>

NOTE: In the above example term textContent is used for accessing the inner content inside the element <p> tag.

Get element by ClassName

Here, elements are accessed using className. It returns all the elements with the same class name used (same class name can be used multiple times in the HTML).

Syntax used:

  document.getElementsByClassName(element_classnames);

Example: Getting elements using the class name.


<body>

    <p class="paragraph-1">hello Jack</p>
    <p class="paragraph-1">hello Mack</p>
    <p class="paragraph-1">hello Jane</p>


   // Javascript inside HTML

     <script>
    //   the get element by className method.

    const paragraphContent=
        document.getElementsByClassName('paragraph-1');

    // console.log(paragraphContent);
    // console.log(paragraphContent.textContent);

     //looping through the object stored in variable 'paragraph'
    for(let i=0;i<paragraphContent.length;i++){
        console.log(paragraphContent[i].textContent);
    /* 

      // Depending on the index i , it will console the value.

      hello Jack
      hello Mack
      hello Jane

     */
    };


    </script>
</body>
</html>

Get element by Name

Here using the name attribute of the HTML elements can access the element from Javascript.It returns all the elements with the name attributes.

Syntax used:

  document.getElementsByName(element_name);

Example: Getting element using name attribute.

 <body>

    <p name="paragraph-1">hello Jack</p>
    <p name="paragraph-1">hello Mack</p>
    <p name="paragraph-1">hello Jane</p>



     <script>
    //   the get element by Name method.

    const paragraphContent=document.getElementsByName('paragraph-1');

    // console.log(paragraphContent);
    // console.log(paragraphContent.textContent);

    for(let i=0;i<paragraphContent.length;i++){
        console.log(paragraphContent[i].textContent);
    };

        /* 

      // Depending on the index i , it will console the value.

      hello Jack
      hello Mack
      hello Jane

     */

    </script>
</body>
</html>

Get element by TagName

Here we will access the element using the tag name instead of only using the name attribute.

Syntax used:

 document.getElementsByTagName(Tag_name);

Example: Getting elements by using tag name. In the below example we have the tag name <p>.

<body>

    <p>hello Jack</p>
    <p>hello Mack</p>
    <p>hello Jane</p>



     <script>
    //   the get element by tag Name method.

    const paragraphContent=document.getElementsByTagName('p');

    // console.log(paragraphContent);
    // console.log(paragraphContent.textContent);

    for(let i=0;i<paragraphContent.length;i++){
        console.log(paragraphContent[i].textContent);
    };

     /* 

      // Depending on the index i , it will console the value.

      hello Jack
      hello Mack
      hello Jane

     */

    </script>
</body>
</html>

Get elements by using CSS selectors

In this method we need a CSS selector for accessing elements from HTML, it could be class, id or the tag name itself. It is to be kept in mind always that we can use the same class name for different elements but when you are using an id it should always be unique i.e we should not use the same id for a different element.

NOTE: Using the same id for different elements works but it is not a good practice to use it, because it should unique

Syntax used: We have two methods through which we can access the elements using CSS selectors are -

document.querySelector(selectors);
document.querySelectorAll(selectors);

Using selectors like.dot followed by class name and # followed by id name we can get the element. In case you want to select only one element by using a CSS selector then you can use the document.querySelector(selectors); or If you want to access more than one element using the CSS selector then you should use the document.querySelectorAll(selectors); this one will return a node list depending on how many elements you have with the same class name.

Example: Let's see an example of both methods.


-----Using querySelector method------

<body>

    <p class="para-content">hello Jack</p>


   <!-- javascript written inside the html -->
     <script>
    //   the get element by ussing CSS selector method.

    const paragraphContent=document.querySelector('.para-content');

    console.log(paragraphContent.textContent);

    /*  output:

             hello Jack



    */

    </script>
</body>
</html>


-----------------------------------------------

------Using querySelectorAll method------



<body>

    <p class="para-content">hello Jack</p>
    <p class="para-content">hello Mack</p>
    <p class="para-content">hello Jane</p>


   <!-- javascript written inside the html -->
     <script>
    //   the get element by ussing CSS selector method.

    const paragraphContent=document.querySelectorAll('.para-content');

    // console.log(paragraphContent);
    // console.log(paragraphContent.textContent);

    for(let i=0;i<paragraphContent.length;i++){
        console.log(paragraphContent[i].textContent);
    };

    /*  output:

             hello Jack
             hello Mack
             hello Jane


    */

    </script>
</body>
</html>

Until now we have seen how elements can be grabbed from HTML now let's see how to handle an event that happens on the page.

Handling Click Event

The events are something that occurs when the user interacts with a system like OS, or browsers . It could be anything like a mouse click, mouse hover, minimizing, resizing and so on. Each event is represented by an object.

(read more about events and types of events here...)

In the case of browser events, there are DOM elements which are meant for accepting and listening to these events, and in return to handle these events it executes some code.

We can attach only one event handler with each and every element, for handling an event from an element we can use a syntax EventTarget.addEventListener method and if you want to remove an event handler from an element you can use EventTarget.removeEventListener.

The addEventListener is a type of function that receives parameters, the first parameter should be the event wrapped with the inverted commas' ', and the second parameter should be the function name, that will be executed when a certain event will occur.There are types of Event handlers such as-

  • click - When the user clicks on a button or link, it attaches a onClick event handler.

Example:

   EventTarget.addEventListener('click', function_name());
  • mouseover - When the user moves the mouse pointer above the link or button, it attaches the onMouseOver event handler.

Example:

  EventTarget.addEventListener('mouseover', function_name());

and like this, there are many more event handlers -

Example: In the example below we want to listen to the event on the button element in the HTML, when the button will be clicked it will listen to the event click and then it will attach a onClick event handler. This will then console the output using the function whenClick().

</head>
<body>

    <p class="para-content">hello Jack</p>

    <button class="btn">click</button>


        <!-- javascript written inside the html -->

    <script>
      //   the get element by ussing CSS selector method.

        const paragraphContent=document.querySelector('.para-content');
        const Button=document.querySelector('.btn');

        const whenClick=function(){
              console.log('clicked!');
        }

        Button.addEventListener('click',whenClick);



        /*  output:

             clicked!

        */

    </script>
</body>
</html>

##Conclusion

DOM is a never ending topic . It is the best idea to always read documentions and blogs about DOM to keep yourself updated.

##Reference