DOM Manipulation In JavaScript

M Khan
6 min readFeb 3, 2020

DOM (Document Object Model) represents the code in a browser. When you visit a website and right click the website you will see an option for inspect. When you click on inspect you can see the source code of the website. This source code is not ALL of the code for the website but the actual Document Object Model of the website. We use JavaScript to “communicate” with the DOM and make changes to the website.

Browsers like chrome come with built in dev tools which allow you to manipulate the JavaScript code. In order to open the dev tools in Chrome, press Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac). You can also use the Ctrl+Shift+J / Cmd+Opt+J to go straight into the console. The console is an environment in the browser where you can type and run JavaScript in the context of the current url you are in.

The DOM is created when the webpage on your browser loads the HTML provided to the browser. The browser reads the HTML, CSS (Styling) and the JavaScript defined in the <link> or <script>. This happens very quickly, so fast that humans can’t perceive it happening. The browser uses all this information to create the webpage that is rendered to the user. If we want to change content we can use a built in object in the browser called document. This document object gives us the information provided in the browser. For example, you can use document.URL to get the url or website address of the website you are currently on. You can also use methods on the document object. For example, you can use document.write(“Hello”) . The properties and methods that the DOM provides to called the DOM’s API or “Application Programming Interface”. The API is the interface in which we can get access to predefined methods and properties for the document object in the browser.

When we view the HTML of a browser we are actually seeing a clone of the HTML found in the source HTML file of the website. The DOM nodes are all the components that make up a web page. The DOM nodes begin very often with a starting tag and ending tag. They can also have other nodes that nest inside of them. The inner nodes are called a child node while the outer node is called the parent node.

Tag Examples

Paragraph Tag

<p>I am a paragraph.</p>

Main Section Tag

<main>

</main>

When we want to nest items to a normal tag we add the child node HTML content between the parent’s starting and ending tags.

Example of a child node inside a parent node

<body>

<main>

<p>I am a child node, inside the main parent node!</p>

</main>

</body>

Some nodes only have a starting tag and they are referred to as self-closing elements. These elements don’t have any content nested inside of them. The more technical term for them are void elements. Void elements cannot be parent nodes.

Example of a self-closing tag (void element)

<img src= “https://media.giphy.com/media/3o6MbkZSYy4mI3gLYc/giphy.gif" alt=”Nissan Sentra” />

*In self-closing tags the / at the end of the tag is optional. We could have written it this way also.

<img src= “https://media.giphy.com/media/3o6MbkZSYy4mI3gLYc/giphy.gif" alt=”Nissan Sentra” >

Query Selectors on DOM

Selecting an Element with JavaScript

We can use special methods on the document object to find different elements of the webpage we are viewing.

Finding Element Example

document.querySelector(‘header’)

The .querySelector will return something similar to this <header class=”site- header”>…</header>. When . you click on the triangle next to the <header you will see the DOM Node which itself is a JavaScript Object. Since the DOM Node is an object you can in turn call methods on the Node as well! This concept is know as method chaining.

We can use method chaining to remove an element in the documents.

Removing an Element Example

document.querySelector(‘header’).remove()

This removes the header element using the second method called .remove and invoked that method using ( ).

Assigning elements to a variable

We can use querySelector to find an element and then assign that element to a variable in order to reference that element using the variable name.

const header = document.querySelector(‘header’)

Query selectors are similar to SQL in that we use query selectors to find different elements in a document object.

The DOM can be represented as a tree where the branches represent parent nodes and branches on those parent nodes represent the children nodes.

DOM TREE

We can use different query methods to find the DOM nodes based on attributes of the DOM nodes.

Different Query Methods for the DOM

  1. document.getElementById( )- used to find the DOM node using the CSS id. CSS ids are unique, if we use this method we will get back only one element.

Example

<div>

<h5 id=”greeting”>Hello!</h5>

</div>

document.getElementById(“greeting”) * single or double quotes can be used around the word greeting.

2. document.getElementsByClassName( )- this method finds elements by class name. Class names do not need to be unique like id so this method will return all the elements with the class name.

Example

<div>

<div class=”banner”>

<h1>Hi!</h1>

</div>

<div class=”banner”>

<h1>Hello?</h1>

</div>

<div class=”banner”>

<h5>“Hellooooo”</h5>

</div>

</div>

document.getElementsByClassName(“banner”)

3. document.getElementsByTagName( ) this method is used if you don’t know the id or class but you do know its tag name. The tag name is the information between <>Examples: h1, header, div etc.

Example.

<main>

<div>

<div>

<p>Hi!</p>

</div>

</div>

<div>

<div>

<p>Hi!</p>

</div>

</div>

<div>

<div>

<p>Hi!</p>

</div>

</div>

</main>

Steps to change the second child element to “Sup”

  1. const main = document.getElementsByTagName(‘main’)[0]
  2. use the method .children to find the second child element of main which points to a div tag.

const div = main.children[1] *index start at 0 so 1 is actually referring to second div element.

3. const p = div.getElementsByTagName(‘p’)[0]

4. The information between the tags is known as the text body aka Hi! We can use the method .textCont to change the text content to Sup.

p.textContent = “Sup”

4. document.querySelector( )-takes in one argument which is a string of CSS-compatible selectors and returns the first element that matches it.

Example

<body>

<div>

<ul class=”ranked-list”>

<li>1</li>

<li>

<div>

<ul>

<li>2</li>

</ul>

</div>

</li>

<li>3</li>

</ul>

</div>

<div>

<ul class=”unranked-list”>

<li>6</li>

<li>2</li>

<li>

<div>4</div>

</li>

</ul>

</div>

</body>

const li2 = document.querySelector(‘ul.ranked-list li ul li’)

we get <li>2</li>

const div4 = document.querySelector(‘ul.unranked-list li div’)

we get <div>4</div>

The . for ranked and unranked indicates that they are class names

IMPORTANT if the class name has spaces in between them you must place a dot after each word so it doesn’t look in the child node.

Example: (.apple.ipad) for class = “apple ipad”

5. document.querySelectorAll ( ) it is similar to querySelector() as it accepts a CSS compatible selector but it returns a NodeList which is a collection of all the matching elements.

Example

<main id=”app”>

<ul class=”ranked-list”>

<li>1</li>

<li>2</li>

</ul>

<ul class=”ranked-list”>

<li>10</li>

<li>11</li>

</ul>

</main>

document.getElementById(‘app’).querySelectorAll(‘ul.ranked-list li’) will return a list of the Nodes that match: <li>1</li>, <li>2</li>, <li>10</li>, <li>11</li>.

Modifying the DOM

We can modify the document using different methods as well using a combination of finding the elements and using different methods to add or remove it.

  1. document.createElement( )-used to create an element of using an HTML tag such as p, div, span, h etc.

Example: let element = document.createElement(‘p’)

In order to get this element to show up on the page you must append it to a node. You can add it to the body using a different method called appendChild( )

2. appendChild( )

Example: document.body.appendChild(element)

You can also add elements using innerHTML

3. innerHTML

Example:

let element = document.querySelector(“p#greeting”);

element.innerHTML = “Hello, Newman!”

If there is a <p>aragraph with id of greeting, our code will grab that and assign it to element.

You can also use innerHTML to add a long strong

Example

let header = document.getElementById(“div#header”);

header.innerHTML = “<h1>Sup!</h1><h3>Lets talk about your daye]</h3><p><em>Sincerely your friend.</em></p>”;

  • There are security concerns with innerHTML as this method can be used to put in nefarious texts or links.

Properties of the DOM can be changed such as the background color.

Example

element.style.backgroundColor = ‘#27647B’

We can also manipulate the DOM using the class name.

Example

  1. element.className = “cat”
  2. element.className = “pet-listing cat”

each class name is put in a string and separated by a space. You can also use other class methods to add or remove class names.

Example

  1. element.classList.remove(“how-are-you”)
  2. element.classList.add(“lets-get-it-done”)

4. removeChild( ) -we can remove a child also using this method.

Example

ul.removeChild(ul.querySelector(‘li:nth-child(3)’))

5. element.remove ( )

Example

ul.remove( )

We learned that we can find the elements of the DOM using different methods such as .querySelector. We can also use other methods to create, remove and alter elements of the DOM as well. With these powerful tools you can visit any website and manipulate the website to your liking.

--

--