Introduction To Document Object Model(DOM)
Tags: javascript, html, webdev, tutorial
Published: 2024-05-08 17:55:27


The **DOM** is an essential concept in web development that enables dynamic access and modification of a web page's content. 

In this article, we will discuss what DOM entails, why it's necessary, and how to use it to manipulate the content of an HTML document. However, before we proceed, it's important for you to have a solid understanding of HTML, CSS, and JavaScript fundamentals. If you're not familiar with these concepts or need a refresher, you can check out the [w3Schools](https://www.w3schools.com) article.



##What is the Document Object Model?

The Document Object Model, often known as ‘DOM’ for short, is the hierarchical representation of document elements in documents such as HTML or XML.

The elements of the documents are represented in a tree order of objects, where each branch of the tree ends in a node. These nodes simply represent parts of the documents, such as elements, attributes, or text strings.
 However, the order in which the nodes are arranged is basically based on the order of creation. The document itself is a node, and its children are referred to as child nodes. Each child node also has its respective children, as explained in the illustration below.
  
  
![The HTML DOM Tree Of Objects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lh3ybk4u5xso56tz7jn.png)


 Why is the Dom Necessary?


The DOM allows us to use interactive programming languages like JavaScript to dynamically access the content of a document and control how it will be displayed in a web browser. It facilitates various types of actions, such as changing the text content, attributes, tags, and styles of the document. 
 Additionally, it handles events in a web browser, such as click events, mouseovers, and keyboard inputs.


### How do we access the document using the DOM?

Before we can access the content of a document, we need to first target the element we want to access, which leads us to **JavaScript DOM Selectors.**

**JavaScript DOM Selectors** are used to select HTML elements or nodes within a document using JavaScript.

####Types of DOM Selectors:

->**getElementById() method**:This method is used to select an element by providing its Id tag.

_Syntax_:

  ```javascript
  const Element = document.getElementById("myId");

  ```
  
With getElementById, we were able to target the element that has an id of “myId"


-> **getElementsByClassName() method**: This method is used to select all the elements that have a specified class name.

_Syntax_:
   ```javascript
   const Element = document.getElementsByClassName("myClass");
   ```

With getElementsByClassName, we can target the element that has a class name of “myClass." 

-> **getElementsByTagName() method**: This targets the elements by specifying their tag name.

_Syntax_
   ```javascript
     const myTag = document.getElementsByTagName("li");
  ```

With getElementsByTagName, we can target all the elements with the tag name “li".

-> **querySelector() method**: This method returns the first element that matches the specified selector.

_Syntax_:
   ```javascript
       const Element= document.querySelector(". example");
   ```
   


-> **querySelectorAll () method**: This method returns all the elements that match the specified selector, unlike the querySelector.

_Syntax_:
  ```javascript
  const Element= document.querySelectorAll(".example);

 ```



####How to manipulate/change the content of an HTML document

After we have targeted the element we want to change using the selectors we discussed earlier, we can now manipulate the content of the HTML using the following methods

-> **innerHTML property**: This allows us to read and update the content of HTML elements.

Example: 
  ```javascript
 const change = document.getElementById("myId"). innerHTML = "Hello People";
```

**Explanation**:

 We target the element with an Id of “myId" and then we use the innerHTML property to change the content to “Hello People".

The code:
  ```html
   <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Change Text</title>
</head>
<body>
  <div Id="myId"> Hello World</div>
  <script> 
    const change = document.getElementById("myId"). innerHTML = "Hello People";
    
  </script>
</body>
</html>

  
 ```

**The output**:

![Code output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hsgockhjkyp6eq4qme8x.jpg)
   

Notice how we changed the div element from "Hello World” to " Hello People.”

-> **Style property**: This property allows you to change the style of an HTML element.

Example: 
  ```
  const change = document.getElementsByClassName("page")[0].style.color("purple");
  ```
**Explanation**: We want to use the style property to change the color of the specified class “page."

The code:
  ``` html
   <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Change Style</title>
</head>
<body>
  <div class="page"> Welcome to my Page</div>
  <div> I like coding</div>

  <script> 
    const change = document.getElementsByClassName("page")[0].style.color("purple");
    
  </script>
</body>
</html>

   ```
  
**Notice**:  We had to use an index to specify the index of the class we wanted to style. That is because getElementsByClassName  returns an array-like collection of elements, not a single element


The output:
   
![Code output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpkb1kjl2sv59se2qlfz.jpg)


-> **Dom Events and Events Listener**: The HTML Dom allows JavaScript to react to an HTML element when an event is triggered.

Events such as when a user clicks the mouse, when a web page loads, or when an input field is changed are then listened for by the Event listener, which performs the required action.

_Syntax_:
   ```javascript
    element.addEventListener(event, function);
   
  ```
**Elements**: This represents the HTML elements you want to add the event listener to.

**Event**: It represents the event type like “click", “mouseOver", “resize”, etc.

**Function**: The code that runs when the event is triggered.

Example:
  ``` html
    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Change Style</title>
</head>
<body>
  <button id="btn">Click Me</button>

  <script> 
    function myBtn() {
      const text = document.getElementById("btn");
      text.innerHTML = "Text has been changed";
    }
    document.getElementById("btn").addEventListener("click", myBtn);
  </script>
</body>
</html>

   
 ```





In this code, we first create our function 'myBtn' that changes the text to 'Text has been changed.' Next, we attach the event listener to our button, specifying the event we want to handle, which is the 'click' event. Finally, we call our function 'myBtn' to execute the desired action when the button is clicked.

The Output:
  
![The output of our code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sxfur1p914oetluh0ozv.jpg)

Notice we changed the text after we clicked the button.

For further comprehensive notes on Event listeners, check out this [article](https://www.w3schools.com/js/js_events.asp).



###Conclusion



In this article, we examined the Document Object Model (DOM) concept.
 We discussed tasks like applying styles, modifying content, and associating event listeners with elements.
 I hope you found this tutorial enjoyable, and I encourage you to solidify your understanding by practicing the discussed methods. 

See you at the top!