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 ❤
Top comments (4)
Hey I'm not sure which captures are you talking about :)
The captures to show the index and app code for:
In a way they're same, cause they fall under category of selecting node/element from the dom.
getElementbyId()
is useful when you target particular id from the DOM, which returns single elementgetElementsByClassName()
orgetElementByTagName()
will return list of matched elements according to what is passed as parameter , there for i used [0] ingetElementByClassName()
, both methods returns list of elementsWhile
querySelector()
is useful to peek class/id/tag by prefixing their css notation (i.e) id root can be #root and class active can be .active, we can also pass tag names here but in all casequerySelector()
returns only first element and not list of elements , if you want list of elements to be selectedquerySelectorAll()
can be usefulRegards.