Enough JavaScript to get you Started : #14 Understanding DOM
Tags: javascript, beginners, webdev, 100daysofcode
Published: 2021-01-20 07:15:57

### What is DOM?

👉 The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.

### Throw this out of the window , I'm Confused 😵
👉 Okay so let me give you a simple definition which will make your concepts clear. DOM represents all the HTML hierarchy for better access in JavaScript -> DOM have document object -> which have all of our HTML elements with structure and styling. 

👉 DOM is there so we can play with elements within JavaScript directly we don't need any intermediate in between HTML and JS. it represent all the HTML elements with their attributes and styling.

### DOM in visual context

![Artboard – 11.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1610104541530/20Degp6ew.png)

### Need of DOM
👉 **Story** : consider making a greeting website which says good morning on the click of button , you can not do that with simple HTML. adding more to it , suppose you want some styling to be applied dynamically that can be only possible through DOM

👉 DOM Creates a snapshot of our HTML code with Hierarchy and can be used to play with HTML directly from JS

👉 in very very simple words , DOM is there so you can manipulate ,add ,remove elements , add / remove styling of elements , get/set/remove HTML attributes like `src` and `href`.

👉 DOM can be used for<br> <br>
👉 Selecting Elements<br>
👉 Manipulating them<br>
👉 Changing their styles and attributes<br>
👉 Adding events statically/dynamically <br>
👉 Traversing through child and parent elements<br>

![JavaScript-DOM-Node-Relationships.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1610104665340/5wYslLtsO.png)

### What we'll be covering? 📓

👉 We'll create a greeting app which will cover selecting and manipulating elements as well as styles 😁

👉 Completing whole DOM is beyond the scope of this article , i strongly suggest you to read full article on  [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction)

👉 We'll go through

1. Selecting Elements
1. Adding events through addEventListener
1. Working with attributes
1. Manipulating Styles 

### Selecting Elements
👉 Selecting Element from DOM can be tricky , though we can select elements with above mentioned techniques

1. `getElementById()` 
1. `getElementsByClassName()`
1. `getElementsByTagName()`
1. `querySelector()`

👉 **getElementById** takes name of id given in HTML and returns node so that we can change or manipulate That node with JS.

👉 in `index.html`

```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>greet</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <h1 class="hide" id="heading1">Hey , How Are you?</h1>
    <br />
    <button id="btn">get greeting</button>
    <script src="app.js"></script>
</body>

</html>
```

👉 in `app.js`
```
// selecting node by id
var greet = document.getElementById("heading1");
// changing text of node
greet.textContent = "Hello world";

```
👉 this JavaScript can select the node with "heading1" and assigns it text of "Hello World"
<hr>

👉 `getElementsByClassName` takes `className` as parameter and returns list of matched nodes who're having className same as param.

👉 in `index.html`

```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>greet</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <h1 class="header">Hey , How Are you?</h1>
    <br />
    <button id="btn">get greeting</button>
    <script src="app.js"></script>
</body>

</html>
```

👉 in `app.js`
```
// selecting node by className
// notice we're selecting first node from the list by writing '[0]'
var greet = document.getElementsByClassName("header")[0];
// changing text of node
greet.textContent = "Hello world";

```
 <hr>
👉 `getElementsByTagName` takes name of tag like `h1`,`p`,`a` as a parameter and returns array of matching node elements from DOM tree. 
 <hr>

👉 `querySelector` takes className or Id as parameter and select the first node element

👉 if we are passing a class then we've to prefix class with `.` like `.active` and if we pass id we've to pass it like `#id` .

👉 in `index.html`

```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>greet</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <h1 id="header">Hey , How Are you?</h1>
    <br />
    <button id="btn">get greeting</button>
    <script src="app.js"></script>
</body>

</html>
```

👉 in `app.js`
```
var greet = document.querySelector("#header");
// changing text of node
greet.textContent = "Hello world";

```

<hr>
### Changing the styling of node elements

👉 Changing the styling of node elements can be done using 2 ways 

1. using style
1. using classList

👉 Changing Background color od body using style property
```
document.body.style.backgroundColor = "red";
```

👉 Appending a css class (red) using ClassList
```
document.body.classList.add("red");
``` 
<hr>

### Changing Attributes of Attributes
👉 Consider you have to change background color or image at runtime, you can't do that statically in HTML

👉DOM also provides methods for setting or manipulating(adding/removing/changing) attributes when some event gets triggered or even without events

👉 Changing Body Color of `<body>` and src of `<img>` with JS
<br>
👉 in `index.html`
```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <img id="img" src="" alt="">
    <script src="./main.js"></script>
</body>

</html>
```
👉 in `main.js`
```
// setting bg color property of body to red
document.body.setAttribute("bgcolor", "red");
// setting src property of img to some image
document
  .getElementById("img")
  .setAttribute("src", "2.jpg");

```
👉 `setAttibute` is used to set value of HTML attributes which takes 2 params namely name of attribute and the value we want to set !

👉 Notice that i've written `document.getElementById("img").setAttribute("src", "2.jpg");
` in code , this is known as method chaining.

👉 method chaining is used to achieve same target but  without storing that node/element in some variables which is not needed (results in code optimization 😁)

👉 In the same way `getAttribute()` takes name of attribute of element and return that attribute's value. 

👉 `removeAttribute()` also takes name of attribute and removes that particular attribute from HTML .

<hr>

### Event Listeners
👉 Event listeners are used to determine what happens when some event is triggered

👉 so , for example i've button in `index.html` and i want to `console.log()` something on the click of button click i've to attach eventListener to button.

👉 in `index.html`
```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="btn">click me</button>
    <script src="./main.js"></script>
</body>

</html>
```
👉 in `main.js`
```
var btn = document.getElementById("btn");

btn.addEventListener("click", function () {
  console.log("hello user");
});

```
👉 `addEventListener` is used for adding event listeners to HTML elements so we can do something with JS as an when that event happens.

👉 `addEventListener` takes 2 params, namely name of event ('click' in our case) and a function which tells events listener what to do when event happens (greeting user in our case).

👉 Notice that this function doesn't have name , these kind of functions are also known as anonymous functions because they're triggered as an when some event happens so they don't need any name.

<hr>

### Making an greeting app
👉 **definition :** when end user clicks on greet button JS need to load image depending on morning time or evening time 

👉 We'll use all of these things which we've learnt previously and `Date()` object which will give us exact hours for passing it into condition and changing content dynamically

👉 in `index.html`
```
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>greet</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <h1 class="hide" id="heading1">Hey , How Are you?</h1>
    <br />
    <button id="btn">get greeting</button>
    <script src="app.js"></script>
</body>

</html>
```

👉 in `app.js`
```
// selecting elements
var btn = document.getElementById("btn");
var greet = document.getElementById("heading1");

// attaching event on click
btn.addEventListener("click", function () {
  // getting exact hour
  var hour = new Date().getHours();
// checking condition  
if (hour <= 12) {
    document.body.style.backgroundImage =
      "url('./morning.jpg')";
    greet.textContent = "Good Morning !";
  } else {
    document.body.style.backgroundImage =
      "url('./evening.jpg')";
    greet.textContent = "Good Evening!";
  }

  document.body.style.backgroundPosition = "center";
  document.body.style.backgroundSize = "cover";
  document.body.style.backgroundRepeat = "no-repeat";
  // hiding button
  btn.classList.add("hide");
  // display the greeting
  greet.classList.remove("hide");
});

```

👉 Praise yourselves, you've came this far 🎉

<p>Let me know in comment section if you have any doubt or feedback. it's always worth to give time to the thriving developer community :) <br>
<br>
Keep Coding ❤
</p>

#### Hey , Let' Connect👋
 [Twitter](https://twitter.com/codarsh) / [Github](https://github.com/WhoAdarshPandya/)