Enough JavaScript to get you Started : #14 Understanding DOM

Enough JavaScript to get you Started : #14 Understanding DOM

Β·

11 min read

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

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

πŸ‘‰ Selecting Elements
πŸ‘‰ Manipulating them
πŸ‘‰ Changing their styles and attributes
πŸ‘‰ Adding events statically/dynamically
πŸ‘‰ Traversing through child and parent elements

JavaScript-DOM-Node-Relationships.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

πŸ‘‰ We'll go through

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

Selecting Elements

πŸ‘‰ Selecting Element from DOM can be tricky , though we can select elements with above mentioned techniques

  1. getElementById()
  2. getElementsByClassName()
  3. getElementsByTagName()
  4. 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"


πŸ‘‰ 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";


πŸ‘‰ getElementsByTagName takes name of tag like h1,p,a as a parameter and returns array of matching node elements from DOM tree.

πŸ‘‰ 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";


Changing the styling of node elements

πŸ‘‰ Changing the styling of node elements can be done using 2 ways

  1. using style
  2. 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");

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
πŸ‘‰ 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 .


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.


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 πŸŽ‰

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 :)

Keep Coding ❀

Hey , Let' ConnectπŸ‘‹

Twitter / Github