Week 5 JavaScript DOM Manipulation Notes
Week 5 JavaScript DOM Manipulation Notes
• 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>
<button onclick="alert('Hello World!')">Click
Me</button>
</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 src="script.js" defer>
</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 someArray = [1, 6, 8];
someArray[1] = 44; // reassigning the 2nd
element of the array
console.log(someArray); // prints [1, 44, 8]
let somePerson = {
name: "Abebe",
education: {
school: "Evangadi",
field: "Full stack",
grade: "3.9"
}
}
somePerson['education']['grade'] = "4.0"; //
reassigning the grade value
console.log(somePerson); // prints object
with updated grade of 4
• 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. Changing
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
• 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:
2: The “element node”: Each HTML tag becomes element node under the DOM tree.
Examples of element node objects include:
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:
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 “bye” 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
▪ 3. Traverse the DOM: Traversing is the act of selecting an element from
another/neighboring element. This is discussed in detail under section 8.9 of this
class.
• 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>
var el = document.querySelectorAll(".yellow");
el.item(0);// selects the first li with yellow class
el.item(1);// selects the 2nd li with yellow class
var el =
document.getElementsByClassName("red");
console.log(el[1]); //selects the 2nd li with
red class
Syntax:
document.getElementsByTagName(tagname)
getElementsByTagName("li"); //returns
HTMLCollection with all <li>
var el = document.getElementsByTagName("li");
console.log(el.item(0));// returns the 1st li
element
console.log(el[1]); // returns the 2nd li
element
Syntax:
document.getElementsByClassName(classname)
getElementsByClassName(“red”)// returns HTML
collection with all elements having the “red” class
var el = document.getElementsByClassName("red");
console.log(el[1]); //selects the 2nd li element
with red class
console.log(el.item(0));// selects the 1st li
element with red class
• HTMLCollection vs NodeList
▪ One thing to understand is that most JavaScript selector methods return multiple
elements with a single query. Because of this, by default many selectors will return
array-like lists that store the matching elements.
• Note: When we use the methods that return multiple elements by default,
even if there is only one matching element in the document, a list will still
be returned.
• Note 2: If you want to do something with an element returned in a list, you
must specifically identify it from the list first in order to properly target it.
There are several ways you can do this.
▪ NodeList: To refresh your memories, everything in the DOM is a node (contains
element nodes, text nodes, atrribute nodes, etc.) NodeList returns a static NodeList.
Meaning, even if the DOM changes after you use the method, the NodeList does not
change and does not reflect the current UI.
• querySelectorAll() method returns a static NodeList.
• HTMLCollection: Element/HTML node in DOM contains only elements. To refresh
your memory, an element node in DOM is one specific type of node, called element
node (it can be <li>, <div>, <body>, etc.) HTMLCollection returns a live
HTMLCollection where, each nodes can be accessed by index numbers 0 being the
first index. Meaning, if the DOM changes after you use the method, the
HTMLCollection is updated to reflect the current UI.
• getElementsByClassName() and getElementsByTagName() methods
return a live HTMLCollection.
▪ NodeList(static collection) vs HTMLCollection (live collection) in example: We
said HTMLCollection returns a live HTMLCollection. Meaning, if the DOM changes
after you use the method, the HTMLCollection is updated to reflect the change. We
also said NodeList returns a static NodeList. Meaning, even if the DOM changes after
you use the method, the NodeList does not reflect the current change.
• Assume this is your html
<div id="my-div">
<p class="firstPar">I am the first paragraph</p>
<p class="secondPar">I am the second paragraph</p>
</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
▪ 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:
▪ 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").las
tElementChi 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").parentE
lement);// 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").previ
ousElement Sibling)//prints the 2nd li
console.log(document.getElementById("two").nextEle
mentSibli 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:
• 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>
• 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
▪ 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 classForLastName=document.getElementsByName("lastName")[0];
classForLastName.classList.add("myLastName");// adds class name
console.log(classForLastName.classList);// prints a DOMToken list
containing the "myLastName" we just added above
var firstInputVal =
document.getElementsByTagName("input")[0];
console.log(firstInputVal.getAttribute("name"));
// returns "firstName" which is the value of the
"name" attribute for first name <input>
var firstInputVal =
document.getElementsByTagName("input")[0];
firstInputVal.setAttribute("value ", "first name
");// placeholder input value of “first name”
added to our <input>
▪ removeAttribute() method: The removeAttribute() method removes the specified
attribute from an element.
• Syntax: element.removeAttribute(attributename)
• Let’s remove the “type” attribute form the first name <input>
var firstInputVal =
document.getElementsByTagName("input")[0];
firstInputVal.removeAttribute("type");// removes
the “type” attribute
console.log(firstInputVal.getAttribute("type"));
// returns null because we just removed the
"type" attribute
<h1 id="title">Fruits</h1>
<div class="containerDiv" id="divID">
<ul id="listOfFruits" class="Kelele">
<li id="one" class="red">Apple</li>
<li id="two" class="yellow">Mango</li>
</ul>
</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>
▪ 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
▪ Style display property: The display property sets or returns the element's display
type. Elements are mostly block or inline. You can also hide the element using
display:none
• 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