Document Object Model (DOM) in JAVASCRIPT

Document Object Model (DOM) in JAVASCRIPT

What is API?

  • Application Programming Interface: A piece of software that can be used by another piece of software, to allow applications to talk to each other.

  • Application refers to any software with distinct functions. On the other hand, the interface can be thought of as a contract of service between two applications.

  • This contract defines how the two communicate with each other using requests and responses.

Examples of API

There are many types of APIs in Web development:

DOM API Geolocation API Own class API

What is Document?

The document , the interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. The Document , the interface describes the common properties and methods for any kind of document.

The Document constructor creates a new Document an object that is a web page loaded in the browser and serves as an entry point into the page's content.

new Document()

What is DOM?

Document Object Model (DOM) is a bunch of objects (Document Object Model) that make up a web page. DOM API is a programming interface for web documents. It allows us to create, change or remove elements from the document. We can also add events to these elements to make our page more dynamic. It allows us to make Javascript interact with the browser. Dom tree is generated from an HTML document, which can then interact with.

Frame-70-1

DOM tree example:

DOM tree generator

The Dom Tree(No its not an actual tree) | by Joseph Chavez | Medium

DOM methods:

DOM is a very complex API that contains lots of methods and properties to interact with DOM tree.

.querySelector() / .addEventListener() / .createElement() / .innerHTML / .textContent / .querySelectorAll() / .getElementById() / .children / etc ...

MethodDescription
.getElementById()Fetch the element by id
.getElementByClassName()Fetch all the elements by className
.getElementsByTagName()Fetch all the elements by Tag name
.querySelector('#id')Find the element by id
.querySelector('.class')Find the element by class name
.querySelectorAll('#id')Find all the elements by id
.querySelectorAll('.class')Find all the elements by class

.getElementById()

In HTML, ids are used as unique identifiers for the HTML elements. This means you cannot have the same id name for two different elements. textContent is used to get the text written on specific DOM elements. heading.textContent = 'It will override heading'; this will change the value of the web page also. Thus now on the web page, it will show "It will override heading" . innerHTML the property also behaves the same as textContent.

<html lang="en">
  <body>
    <h1 id="heading">Hey, Good Morning</h1>

    <script>
        const heading = document.getElementById("heading");
        console.log(heading); // <h1 id="heading">Hey, Good Morning</h1>
        console.log(heading.textContent); //Hey, Good Morning
        heading.textContent = 'It will override heading';
        console.log(heading.textContent); // It will override heading
        console.log(heading.innerHTML); // It will override heading
    </script>
  </body>
</html>
<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="abc.gif">
<script>
document.getElementById("myImage").src = "xyz.jpg";
</script>
</body>
</html>

.getElementByClassName()

<!DOCTYPE html>
<html lang="en">
  <body>
    <h1 class="heading">Heading 1</h1>
    <h1 class="heading">Heading 2</h1>

    <script>
        const heading = document.getElementsByClassName("heading");
        // heading return an array of elements which are all having "heading" as cls
        console.log(heading); // HTMLCollection(2) [h1.heading, h1.heading]        
        console.log(heading[0]); // <h1 class="heading">Heading 1</h1>
        console.log(heading[0].textContent); // Heading 1
        console.log(heading[1]); // <h1 class="heading">Heading 2</h1>
        console.log(heading[1].textContent); // Heading 2
    </script>
  </body>
</html>

.getElementsByTagName()

<html lang="en">
  <body>
    <h1 class="heading">Heading 1</h1>
    <h1 class="heading">Heading 2</h1>

    <script>
       const heading = document.getElementsByTagName("h1");
       console.log(heading); // HTMLCollection(2) [h1.heading, h1.heading]
       console.log(heading[0]); // <h1 class="heading">Heading 1</h1>
       console.log(heading[0].textContent); // Heading 1
       console.log(heading[1]); // <h1 class="heading">Heading 2</h1>
       console.log(heading[1].textContent); // Heading 2
    </script>
  </body>
</html>

.querySelector()

<!DOCTYPE html>
<html lang="en">
  <body>
    <h1 class="heading1">Heading 1</h1>
    <h1 id="heading2">Heading 2</h1>

    <script>
        // select element by class name
        const heading1 = document.querySelector(".heading1");
        console.log(heading1); // <h1 class="heading1">Heading 1</h1>
        console.log(heading1.textContent); // Heading 1

        // select element by id
        const heading2 = document.querySelector("#heading2");
        console.log(heading2); // <h1 id="heading2">Heading 2</h1>
        console.log(heading2.textContent); // Heading 2
    </script>
  </body>
</html>

.querySelectorAll('.class')

It will return a node list in which you can traverse and get the elements one by one.

<!DOCTYPE html>
<html lang="en">
  <body>
    <h1 class="heading">Heading 1</h1>
    <h1 class="heading">Heading 2</h1>

    <script>
       const allHeadingByClass = document.querySelectorAll(".heading");
       console.log(allHeadingByClass); //NodeList(2) [h1.heading, h1.heading]
       allHeadingByClass.forEach((ele) => {
          return console.log(ele); // <h1 class="heading">Heading 1</h1>
                                  //  <h1 class="heading">Heading 2</h1>
        });   
        allHeadingByClass.forEach((ele) => {
          return console.log(ele.textContent); // Heading 1
                                              // Heading 2
        });   

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

.querySelectorAll('#')

<html lang="en">
  <body>
    <h1 id="heading">Heading 1</h1>
    <h1 id="heading">Heading 2</h1>

    <script>
       const allHeadingByClass = document.querySelectorAll(".heading");
       console.log(allHeadingByClass); //NodeList(2) [h1.heading, h1.heading]
       allHeadingByClass.forEach((ele) => {
          return console.log(ele); // <h1 class="heading">Heading 1</h1>
                                  //  <h1 class="heading">Heading 2</h1>
        });    

        allHeadingByClass.forEach((ele) => {
          return console.log(ele.textContent); // Heading 1
                                              // Heading 2
        });    
    </script>
  </body>
</html>

HTML forms and DOM

.addEventListener method attaches an event handler to an element. .value reads the value from input field. By default type of value is a string.

<!DOCTYPE html>
<html lang="en">
  <body>
    <input type="text" id="txtInput" />
    <button id="btn">Submit</button>
    <script>
        const inputFieldValue = document.getElementById("txtInput");
        const btn = document.getElementById("btn");
        btn.addEventListener("click", function (e) {
          e.preventDefault();
          console.log(inputFieldValue.value);
        });
    </script>
  </body>
</html>

DOM manipulation with CSS

<!DOCTYPE html>
<html lang="en">
  <body>
    <h1 id="heading">Heading</h1>
    <script>
        const heading = document.getElementById("heading");
        heading.style.color = "red";
        heading.style.backgroundColor = "blue";
        heading.style.width = "50%";
        heading.style.textAlign = "center";    
   </script>
  </body>
</html>

Conclusion:

This blog will give a kickstart and get you familiar with DOM API. There are a lot of DOM methods that you can try out on your own. I have covered all the important ones. As a developer, you should always try out and see the result by yourself.

Feel Free to reach out to me : https://linkfree.eddiehub.io/abhijeet-26