8 JavaScript DOM Manipulation
8 JavaScript DOM Manipulation
• We covered the relationship between HTML, CSS and JavaScript when we discussed the
class on Introduction to Programming Basics. We said HTML provides the basic structure
of websites, which is enhanced and modified by other technologies like CSS and
JavaScript. CSS is used to control presentation, formatting, and layout. JavaScript is a
logic-based programming language that can be used to modify website content and make
it behave in different ways in response to a user's actions.
• In short, the relationship between HTML, CSS and JavaScript is explained below:
▪ HTML defines the structure of a web page
▪ CSS provides the style/look of the HTML page
▪ JavaScript adds interactivity to the HTML page
• We have also covered the different ways we can include JavaScript into our HTML under
1.7 section of phase 2. However, it is important to revise this section before diving into
DOM.
• Just like HTML and CSS, JavaScript is also a text file. HTML file uses. There are different
ways of including JavaScript in our HTML.
• Including JavaScript code inline:
▪ Insert your JavaScript code directly inside the HTML tag using the special tag
attributes such as onclick, onmouseover, onkeypress, onload, etc. Example:
<body>
</body>
▪ Note: You should avoid placing large amount of JavaScript code inline as it
clutters up your HTML with JavaScript and makes your JavaScript code difficult
to maintain
• Embedding the JavaScript Code in your HTML:
▪ Embed the JavaScript code directly within your web pages by placing it between
the <script> and </script> tags.
▪ The <script> tag indicates the browser that the contained statements are to be
interpreted as executable script and not HTML. Here's an example:
<body>
<script>
function someFunction() {
alert ('Test');
someFunction();
</script>
</body>
<script src="script.js"></script>
▪ Once you include your external JavaScript file into your HTML, you can use the
"console.log()" method to display what you want on the console. Below is an
example of code you will write if you want the code to log “Hello World” on the
console: console.log("Hello World")
▪ Recommended place to add the <script> tag:
• Adding <script> tag at the bottom: If we include our <script> tag within
our html <head> tag, the HTML parser on our browser loads and executes
the script as soon as it encounters it. In modern websites, scripts are often
“heavier” than HTML, so, their download size is larger, and processing
time is also longer. It is recommended to add our <script> tag at the bottom
in our <body> tag because we want the HTML and CSS to finish loading
before our JavaScript. Putting the <script> tag at the bottom allows the
browser to see the HTML elements above the script, and it doesn’t block
the HTML page content from showing. For example, if our JavaScript is
having issues or we have a slow internet connection, the browser will still
load the rest of the page and doesn't "hang".
• “defer” attribute: If we include our <script> tag within our html <head>
tag, we have to add the "defer" attribute to tell the HTML parser to load
the script after it finishes loading all of our HTML elements. The defer
attribute tells the browser not to wait for the script. Instead, the browser
will continue to process the HTML and build the page. Note that, "defer"
is an attribute that is added on HTML 4 just for this purpose. Example:
<head>
</script>
</head>
• HTML is a markup language. JavaScript is a programing language that usually deals with
objects. How do they work together then?
• From what we have learned so far, we can manipulate data types like array using
JavaScript. We have also seen how we can access and manipulate JavaScript objects.
▪ Example of manipulating array:
let somePerson = {
name: "Abebe",
education: {
school: "Evangadi",
grade: "3.9"
• What if we have a way to convert the HTML elements into a structured object like
the "somePerson" and try to manipulate the elements?
▪ If we can convert the HTML elements into an object form, we can apply the
JavaScript object manipulation techniques on them, right?
▪ To do this, DOM is the answer for that
• What is the DOM Object?
▪ DOM (Document Object Model) explained in plain English:
• Assume you have your TV on, but you want to change the show that's
being streamed, and you also want to increase the TV’s volume. Chaning
the show and increasing the TV’s volume needs a way by which you
interact with your television, a remote. The remote is basically the bridge
that allows you to interact with your television. You make the TV interact
with you via the remote. You make HTML interact with you via JavaScript
by using DOM. Just like your TV can't do much without the remote,
JavaScript doesn't do much (other than doing some calculations or work
with basic strings) to make HTML interactive without using DOM to
select and update the HTML elements.
• We know that JavaScript needs to access the HTML document and it also
needs to know when the user is interacting with the HTML. It is through
DOM structure that JavaScript can access and update the HTML document
whenever a user interacts with the HTML.
• For example, if you want a button on your website to change its color to
green when a user clicks on this button, you need to be able to select this
specific button and write a logic that changes the color of the selected
element into green using JavaScript. DOM organizes our HTML
document in an object form so that JavaScript can manipulate (access and
modify/update the any HTML element). Therefore, DOM is the link
between an HTML web page and JavaScript.
▪ DOM explained in terms of programming:
• The DOM is a structure/standard/syntax that allow JavaScript to access,
modify, and update the structure of an HTML page.
• The DOM is a logical tree-like model/representation of our HTML. DOM
represents the HTML page using a series of objects. The main object is the
document object, which in turn houses other objects which also house their
own objects, and so on. Click on the below link to look at the diagram
explaining DOM:
https://content.codecademy.com/courses/dom/dom_revision_1.svg
• Understanding the DOM
▪ Why do we need to understand DOM? As a Frontend developer, your job will
be to select and update the DOM elements when user interacts with a website.
Selecting and updating HTML elements using JavaScript is possible if one has a
good understanding of what DOM is. This is where you apply your basic
programing skills
o Selecting DOM elements: It simply means locating the element
you want to work with
o Updating DOM elements: It means interacting with the element,
the text of the element, the attributes of the element or with its
child elements
• Relationship between the browser and DOM: How does a website work?
▪ Webpage:
• A webpage is a properly tagged HTML text document. The main purpose
of a web page is to display the text information that is included in the
document in a well-organized and visually meaningful way to the user.
• As a web page is simply a text document, we would need help to create
some useful visual representation of the text. A software that helps us
create a useful visual representation is called a Browser. This means a web
page without the help of the browser is as helpless as a text document.
▪ The browser/web browser:
• In common usage, a web browser is usually shortened to "browser."
• Web browser is a software program that loads files from a remote server
(or perhaps a local disk) and displays them to a user. The main role of a
web browser is to create a visual representation of the HTML document
based on the tags used on the text document.
• The process of creating the visual representation of the HTML file t is
called rendering. For the browser to be able to render your HTML file, it
needs to get the HTML tagged text first. When the HTML file is saved
locally, all the browser needs is a way to locate this resource file
containing the HTML. The way we achieve this is by giving the URL
(Uniform Resource Locator) to the browser. Since we are on a local
computer this URL is just the path to the file. Path is structured by the
Operating System on the computer.
• Within the browser software, there is a piece of software that locates the
URL of the resource file containing the HTML and figures out what to
display to you based on the HTML files it receives. This is called the
browser engine.
• When you write some HTML, CSS, and JS, and attempt to open the
HTML file in your browser, the browser reads the HTML from your hard
disk. To read your HTML file, the browser transforms your HTML into
object via DOM.
• Common web browsers include Google Chrome, Firefox, Apple Safari,
Mozilla, and Microsoft Edge.
▪ How does a browser render/build an HTML web page?
• When a web page is loaded, the browser first reads the HTML text, then
browser creates nodes from the HTML document and it will create a tree-
like structure of these node objects, the DOM tree. A DOM tree starts from
the topmost element which is the <html> tag and branches out to the
HTML elements nested under the <html> tag.
o Whenever the browser encounters a script tag, the DOM
construction is paused. The entire DOM construction process is
halted until the script finishes executing. This is because
JavaScript can alter both the DOM tree and the CSS tree. That is
why the location of your script tag in your HTML file matters. If
you add the “async” or “differ” keyword to the script tag, the
DOM construction will not be halted.
o Note: We discussed previously that browser understands only
HTML and CSS. For the browser to understand the code on our
JavaScript file, every browser has a JavaScript engine that takes
our JavaScript code and converts it into something that the
browser can understand
• After constructing the DOM tree, the browser reads CSS from all the
sources (external, embedded, inline, user-agent, etc.) and construct a CSS
object model which is a tree like structure just like DOM. Each node in
this tree contains CSS style information that will be applied to DOM
elements that it targets (specified by the selector)
• After constructing these two trees, the browser then combines these trees
together. The combined tree-like structure is called Render Tree. Once the
Render-Tree is constructed, then the browser starts the printing individual
elements on the screen. Note, if the browser constructed the HTML and
CSS, there is no page to be printed on the screen unless Render-Tree isn’t
constructed.
▪ Here is a diagram showing the interactions of HTML, CSS and JavaScript
files with the browser
• https://www.oreilly.com/library/view/php-
mysql/9781449355517/httpatomoreillycomsourceoreillyimages1416220.
png.jpg
• Note:
▪ DOM is not part of HTML
▪ DOM is not part of JavaScript. However, JavaScript interacts with the created
DOM object
▪ DOM is a language-agnostic structure. Meaning, DOM can interact with various
languages other than JavaScript
8.4 The DOM tree
• The DOM tree: When the browser reads HTML code and encounters an HTML element
like <html>, <body>, <div>, or encounters HTML attribute like “src” and “ref” or texts in
HTML, it converts each one of them into objects. The objects the browser creates from our
HTML document are called a node. After the browser has created node objects from the
HTML document, it will treat the node objects as a tree-like hierarchy.
▪ DOM node: In DOM terminology, all elements of an HTML document are nodes,
including the built-in DOM elements such as document document.body, HTML
tags such as <p> (called element node), a text in HTML tags (text node) and an
attribute (attribute node) of an HTML tag. DOM nodes are any one of the above
in an object form in the DOM hierarchy. Thus, node objects have methods in them
that we can use to access and alter them.
▪ Dom element: DOM element on the other side is one type of a DOM node
representing only HTML elements. Meaning, an element node is a node that's
written using a tag in the HTML document. <html>, <head>, <title>, <body>,
<h2>, <p> are all elements because they are represented by tags. <!DOCTYPE >,
the comment and the text nodes are not DOM elements
• In simple terms, we can say DOM tree is constructed from nodes. There are 12 node types
available to build the DOM tree. However, we will focus below on the five most used node
types present in almost all HTML documents.
• The common node types under the DOM tree: Please note than under the DOM tree, all
the below nodes are represented as objects.
▪ 1. The “document node”: Document node is the root of DOM tree. It represents
the entire HTML document that is loaded in the browser window. It is the entry
point to the document. The document node has multiple methods that we can
access all nodes in the DOM tree. Also, the top-level nodes in an HTML document
(<html>, <head>, <body>) can be directly accessed using properties of document
node as follows:
• document.documentElement to access the <html> tag
• document.head to access the <head> tag
• document.body to access the <body> tag
▪ 2: The “element node”: Each HTML tag becomes element node under the DOM
tree. Examples of element node objects include:
• <html>, <head>, <body>, <h1>, </div>, <p>
▪ 3: The "attribute node”: Each attribute of an HTML element becomes element
node under the DOM tree. Once again, attribute nodes are also objects. Means they
have their own method that we can use to read or change the attribute values.
Examples of attribute node objects: <html lang="en-US">, <a href="">, <img
src="" width="" alt="">, <div id=""> <p style="">, etc.
▪ 4. The "text node”: Text nodes represents the textual content in an element or an
attribute. Examples of text node objects include:
▪ <p> Some text </p>
• 5. The "comment node”: HTML comments (<!-- comment -->) are represented
by comment nodes in a DOM tree. That means, comment node can also be accessed
using JavaScript. You may be asking yourself “why is a comment added to the
DOM, if it doesn’t affect the visual representation of an HTML?”. However, there
is a rule under DOM stating that anything in the HTML must be represented in the
DOM tree. Meaning, everything in HTML, even comments, become a part of the
DOM.
• Refer to the following links/diagrams to see how the DOM tree represents the HTML
elements, attributes and texts as objects.
o https://content.codecademy.com/courses/dom/dom_revision_1.svg
o https://miro.medium.com/max/1040/1*YSA8lCfCVPn3d6GWAVokrA.png
o https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/DOM-
model.svg/1200px-DOM-model.svg.png
8.5 DOM manipulation: introduction
• JavaScript is most used language to modify HTML elements or their content and apply
effects like show/hide, animations, etc. But before we perform any action on an element,
we need to select the target HTML element.
• What does selecting DOM elements mean? In terms of DOM manipulation, the term
“selecting” an element(s) means finding an element that we plan to manipulate or apply a
change on.
• Selecting in JavaScript can also be divided into three types
▪ 1. Select an individual element:
• Example: Finding one specific <div> element
▪ 2. Select multiple elements: Example:
• Finding all <div> elements
▪ 3. Traversing between multiple elements:
• Example: Finding a <p> element within a particular <div>
• Selecting an individual element: There are three common methods provided by the
document object that we can use to select one specific element. Let’s look at them below.
▪ 1. getElementById() method: The getElementById method accepts CSS’ id
selector as its argument and returns an element whose id matches the passed
string/id. Since the ids of elements are always unique to that element, this is a faster
way to select an element. If the id is not found, then this method returns null.
▪ 2. querySelector() method: The querySelector method takes CSS selectors as its
argument and returns the first element that matches the passed selector. Meaning,
the method can take ids, classes and tag names as its argument.
• document.querySelector("#hi"); // selects the element with “hi” id name
• document.querySelector(".bye"); // selects all elements with “hi” class
name, but returns first element in the document with class name
• document.querySelector("div"); // selects all elements with “div” tag, but
returns first div
• document.querySelector("div span.hello"); // selects all “span” elements
within a “div” tag but returns the first span element with class name
"hello", inside a div
• Selecting multiple elements: There are three common ways of selecting multiple elements
with just one query. Please note that, you can pass in any valid CSS selector for these
methods, including, comma-separated CSS selectors for targeting multiple different
selectors.
▪ querySelectorAll() method: The querySelectorAll() method returns all elements
in the document that matches a specified CSS selector(s) as NodeList.
• Syntax: document.querySelectorAll(CSS selectors)
<ul id="listOfFruits">
<li class="red">Apple</li>
<li class="yellow">Mango</li>
<li class="yellow">Peach</li>
<li class="red">Rasberries</li>
</u>
<div id="my-div">
</div>
• Assume you have your script below: If you add a third paragraph into
the above HTML document dynamically (using JavaScript) and check the
length of the list
o Using the querySelectorAll() method returns a Nodelist and the
length of the collection containing paragraphs will not update
from 2 to 3 even if a new paragraph is added dynamically. This is
because querySelectorAll() returns a static/non-live collection of
items
o Using the getElementsByTagName() method returns an
HTMLCollection and the length of the collection containing the
paragraphs will update from 2 to 3 after a new paragraph is added
dynamically. This is because methods like
getElementsByTagName() and getElementsByClassName()
return a live collection of items
• Look at the script below to explain static and live collections
console.log(staticList.length); // prints: 2
console.log(liveList.length); // prints: 2
thirdPar.className = "thirdPar";
document.getElementById("my-div").appendChild(thirdPar);
console.log(staticList.length); // prints: 2
console.log(liveList.length); // prints: 3
▪ Note: If you have a situation where the DOM is going to be changing and you
specifically want your collection of elements to reflect the current UI, a method
that returns a live list is a better option.
8.9 Selecting elements (traversing between multiple elements)
• Traversing between multiple elements: Traversing is the act of selecting an element from
another/neighboring element.
• Traversing directions: we can traverse in three directions:
</ul>
</div>
▪ Traversing downwards:
• firstElementChild(): The firstElementChild property returns the first
child element of the specified element.
console.log(document.getElementById("listOfFruits").firstEleme
ntChild);// prints the first li element under the ul
console.log(document.getElementById("fruitId").lastElementChi
ld);// prints the last li element under the ul
▪ Traversing upwards:
• parentElement(): parentELement is a property that lets you select the
parent element. parentElement is great for selecting one level upwards
console.log(document.getElementById("one").parentElement);//
prints the <ul> which is the parent to all the <li>
• closest(): To find an element that can be multiple levels above the current
element, you use the closest method. closest lets you select the closest
ancestor element that matches a selector.
console.log(document.getElementById("one").closest(". hello"));
//prints the closest parent or the <ul>.
o Note: The <li>s selected here has the <div> and <ul> as its
parents, but closest allows us choose the closest parent
▪ Traversing sideways:
• previousElementSibling: The previousElementSibling property returns
the previous element of the specified element, in the same tree level. Look
at the example above:
console.log(document.getElementById("three").previousElement
Sibling)//prints the 2nd li
console.log(document.getElementById("two").nextElementSibli
ng); // prints the 3rd li
• Question to ask: Why do we need to learn to traverse the DOM? When can we easily use
document.querySelector() ? Let’s look at this example:
</ul>
</div>
• At the beginning of this class, we said that there are two steps involved in DOM
manipulation: selecting elements and altering the element, its text content or its attributes.
We have spent a lot of time on selecting elements. It is now time to discuss on altering
• Altering HTML content: The HTML DOM allows JavaScript to change the content of
HTML elements. Meaning, we can add, update or remove the HTML tag, the text content
in an HTML element, or the entire block of HTML code from your page. These are the
most common methods that allow us add, update or remove contents in an HTML
document.
• Let’s use the below HTML document as an example to explain altering:
<div id="bigId">
<div>Hello</div>
<ul id="listOfFruits">
<li id="one" class="red">Apple</li>
<li id="two" class="yellow">Mango</li>
</ul>
</div>
▪ createElement() method: The createElement() method creates an Element Node
with the specified element name.
• Syntax: document.createElement(nodename)
• Note 1: After the element is created, use the element.appendChild() or
element.insertBefore() method to insert it to the HTML document.
• Note 2: HTML elements often contains text. To insert a text into the
element you created, use the innerText or innerHTML properties.
• Let’s create a new <li> and insert it as the last child of our <ul>
parent.appendChild(liElem);
parent.prepend(liElem2);
• Working with attributes: This is when you want to add, change or remove the attribute
value of an element. Let’s use the example code below to explain how we can alter
attributes
</form>
▪ className() method: The className property sets or returns the class name of
an element (the value of an element's class attribute). Note: To apply multiple
classes, separate them with spaces, like "test demo"
• Syntax: HTMLElementObject.className
• Let’s add 2 class names for <form> and print the added class names
var myForm = document.getElementById("formID");
myForm.className = "formClass1, formClass2"; // "formClass1" and
"formClass2" class names added
console.log(myForm.className);// prints formClass1, formClass2
console.log(myForm.classList); // Also prints a list containing the new
class names "formClass1" and "formClass2"
▪ ClassList() method: The classList property returns the class name(s) of an
element. This property can be used to add, remove and toggle CSS classes on an
element.
• Syntax: element.classList
• Let’s add a class name for our last name <input> and print the added
class name
var classForLastName=document.getElementsByName("lastName")[0];
var firstInputVal =
document.getElementsByTagName("input")[0];
<h1 id="title">Fruits</h1>
</div>
▪ Style color property: The color property sets or returns the color of the text.
• Let’s add “red” color to the text of the first <li>
var firstLi = document.getElementById("one");
▪ Style font property: The font property sets or returns up to six separate font
properties, in a shorthand form. With this property, we can set/return the following
font properties in the order they are written; font-style, font-variant, font-weight,
font-size, line-height and font-family.
• Let’s add font (font-weight, font-size and font-family) to our 2nd <li>
and print the font values we just added
• Let’s change the display property of our <li> into none and print the
changed display
▪ Style border property: The border property sets or returns up to three separate
border properties, in a shorthand form. With this property, you can set/return one
or more of the following (in any order): border-width, border-style and border-
color.
• Let’s change the border property of our <div> into thick, solid, and
red and print the properties