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
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
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
- Selecting Elements
- Adding events through addEventListener
- Working with attributes
- Manipulating Styles
Selecting Elements
π Selecting Element from DOM can be tricky , though we can select elements with above mentioned techniques
getElementById()
getElementsByClassName()
getElementsByTagName()
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
- using style
- 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 β€