Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

DOM Manipulation in JavaScript

The Document Object Model (DOM) is a hierarchical representation of an HTML document, allowing developers to manipulate webpage elements as objects. It provides various methods for selecting and modifying elements, such as getElementById, getElementsByClassName, and querySelector. Understanding DOM manipulation is essential for creating dynamic web applications that can update content without refreshing the page.

Uploaded by

yahyeahmett55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

DOM Manipulation in JavaScript

The Document Object Model (DOM) is a hierarchical representation of an HTML document, allowing developers to manipulate webpage elements as objects. It provides various methods for selecting and modifying elements, such as getElementById, getElementsByClassName, and querySelector. Understanding DOM manipulation is essential for creating dynamic web applications that can update content without refreshing the page.

Uploaded by

yahyeahmett55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

What is the DOM?

DOM stands for Document Object Model. But what does that mean? Let's break it down.

The Document part refers to the webpage you see in the browser. Specifically, the
HTML Document which handles the structure of the page's content. This includes the
text, images, links, and other elements that make up the page.
Object means the elements like images, headers, and paragraphs are treated like
objects. Each object has its properties (like id, class, style) and methods. Using these
properties and methods, you can manipulate the elements.
The Model in DOM means it's a representation or copy of the HTML document as a
hierarchical tree. This tree includes all the elements. And it captures the parent-child
relationships between them.
The DOM is always identical to the HTML document. Browsers ensure that they are in
sync. So, if something changes in the HTML, the DOM changes too, and vice versa.

A graphical representation of the HTML DOM tree


At the top of the hierarchy is the Document object. It has only one child –
the html element. The html element, also known as the root element, has two children,
the head and body elements. And each of them also have their own children elements.
The parent-child relationship between the elements is what allows you to traverse or
move between and select them. More on that later.

What You Can Do With the DOM


DOM manipulation allows developers to interact with the structure, style, and content of
web pages. The following are some of the things you can do with the DOM:

• Change and remove existing elements in the DOM.


• Create and add new elements to the page.
• Change the styles for elements.
• Add event listeners to the elements to make them interactive.
How to Select DOM Elements
To do something with DOM elements, you first have to select or access the element in
question. In this section, you will learn some common methods for selecting DOM
elements.

Let's use the following phonebook markup to show how the various DOM selector
methods work.

<h1 id="page-title">Phonebook</h1>

<p class="family">Marie</p>
<p class="family">Jose</p>
<p class="work">Anne</p>
<p class="work">Joan</p>
The markup includes a header with an id of page-title and four paragraphs. The first two
paragraphs both have a class of family, and the last two have a class of work.

1. getElementById
You use this method to select elements with an id attribute. Ids are unique identifiers.
For example, if a header element has an id attribute with a value of "page-title", no
other element on the page should also have an id with the same value.

This means anytime you use the getElementById method, you are going to select only
one element from the DOM.
Let's look at an example:
The h1 header has an id value of page-title. Here is how you can select it using
the getElementById method:
const titleElement = document.getElementById("page-title")
console.log(titleElement)
The example selects the header element and assigns it to the titleElement variable.

Result of accessing element with getElementById method.


If there's no element in the DOM with the given id, the getElementById() method will
return null.

2. getElementsByClassName
You can use this method to select more than one object. This method takes in the value
of a class attribute as an argument and selects all elements in the DOM that has the
given class. Unlike ids, you can give the same class value for different HTML elements.

Here's an example:

const famContacts = document.getElementsByClassName("family")


console.log(famContacts)
This returns an HTML collection of all elements with the given class. The log statement
will print the following in the console:

The getElementsByClassName() method returns an HTML collection.


Note: The HTML collection looks like an array, but it is not. You can access the elements
using bracket notation just as you would with an array – but you cannot apply array
methods like map, filter, and forEach on it.
console.log(famContacts[0])
This will get the first element in the HTML collection, which is the paragraph with the
name Marie.

Result of accessing HTMLCollection element with bracket notation.

3. getElementsByTagName
This method will select elements using their tag name. For
example, getElementByTagName('p') will select all paragraphs on the page.
Like getElementsByClassName, this method also returns an HTML collection of the
selected elements.
Here's an example:

const allContacts = document.getElementsByTagName('p')


console.log(allContacts)

An HTMLCollection containing all paragraph elements.


You can create an array from the HTML collection and use any of the array methods on
it.

let allContactsArray = [...allContacts]

allContactsArray.map(element => console.log(element))

Result of using the map method on allContactsArray.


4. querySelector
You can use this method to select any HTML element in the DOM. It returns only one
element: the first element that matches the given selector.

The querySelector method works like how CSS selectors work.


For example, what do you do when you want to select an element with an id? You use
the hash # symbol. How about when you want to select elements with a class? You put a
dot . in front of the class name.
Here's an example:

const firstWorkContact = document.querySelector('.work')


console.log(firstWorkContact)

An example of using the querySelector method.


The example above returns only the first element with a class of work and ignores the
rest.
Let's see another example to show how querySelector works like CSS selectors. The
following is a div element with four buttons:
<div>
<button>First button</button>
<button>Second button</button>
<button>Third button</button>
<button>Fourth button</button>
</div>
Assuming you wanted to select the third button, you could use querySelector like the
one below. The code uses the CSS nth-child selector to get the third button inside the
div.
const thirdBtn = document.querySelector('div button:nth-child(3)')
console.log(thirdBtn)
Result of selecting the third button with querySelector method.
But what if you want to select all four button elements and not only the first one? Then
you could use the querySelectorAll method instead.

5. querySelectorAll
Like the querySelector method, querySelectorAll also selects HTML elements using CSS
selectors. The difference is that it returns all elements that match the selector instead of
returning only the first one.
Using the previous example, let's select all the buttons with querySelectorAll.
const allBtns = document.querySelectorAll('button')
console.log(allBtns)

The querySelectorAll method returns a NodeList of selected elements.


Note: querySelectorAll returns a NodeList. A NodeList is slightly different from an HTML
collection. You don't need to convert it to an array to apply a method like forEach on it.
allBtns.forEach(btn => console.log(btn))
How to Change the Content of DOM Elements
So far, you've learned about different ways to select DOM elements. But that is only the
beginning. Now, let's see how you can manipulate the DOM to change the content of a
webpage.

The first thing you need to do is to select the element. You can do that using any of the
methods you learned from the previous section.

After selecting the element, there are several methods you can use to add or update the
content.

The innerHTML Property


This is a method that allows you to read or update both the structure and content and
structure of elements. Let's see an example of how you can use the innerHTML method.
The following is some markup of three paragraphs, each with an id.

<p id="topic">JS array methods</p>


<p id="first-method">map</p>
<p id="second-method">filter</p>

Simple markup with three paragraph elements


You can read or get the content of the any of the paragraphs using innerHTML. For
example, let's get the content of the first paragraph.
const topicElement = document.querySelector('#topic')
console.log(topicElement.innerHTML)

Log statement of the innerHTML of the topicElement


Now, let's say you want to update the topic from "JS array methods" to "JavaScript array
methods". You can do that by assigning the new text to the innerHTML of the element.
const topicElement = document.querySelector('#topic')
topicElement.innerHTML = "JavaScript array methods"

The topic is updated from "JS Array methods" to "JavaScript array methods"
With innerHTML, you can change more than just the content. You can also change the
HTML structure of the element. For example, if you want to make the word "JavaScript"
bold, you could do this:
topicElement.innerHTML = "<b>JavaScript</b> array methods"

The word "JavaScript" is made bold using innerHTML


Security Risks With innerHTML
Using the innerHTML poses potential security risks. An example is cross-site scripting
(XSS) attacks.
If the content you're inserting comes from user input or any untrusted source, be sure to
validate and sanitize it before using innerHTML to prevent XSS attacks. You can use a
library like DOMPurify to do this.
Also, if you are working with plain text content, consider using methods
like innerText and textContent.
The innerText and textContent Properties
Both innerText and textContent ignore HTML tags and treat them as part of a string.
You can use both methods to read or update the text of DOM elements.
A key difference between the two is in how they treat the text.
Using innerText returns the text as it appears on the screen. And
using textContent returns text as it appears in the markup. Let's see an example below.
<p>Key =<span style="display: none;"> ABC123<span></p>

A paragraph element with the some text and a hidden span element inside
The example includes a paragraph element. Inside the paragraph is a span that contains
a key. The key does not appear on screen because its inline style is set to a display of
none.

Now, let's select the paragraph and print both the innerText value and textContent value
to see the difference.
const paragraph = document.querySelector('p');

console.log("innerText: ", paragraph.innerText)


console.log("textContent: ", paragraph.textContent)

Result of log statement for innerText and textContent.


Note how innerText returns the text as it appears on the screen (without the value of the
key which is hidden with CSS). And note how textContent returns the text including
hidden elements and whitespaces.
Let's see another example for adding text to an element. The following code includes
two paragraphs, each with bold text and an empty span, as well as a horizontal line
between them.

<p>
<b>innerText Example</b>
<span id="inner-text"></span>
</p>

<hr>

<p>
<b>textContent Example</b>
<span id="textContent"></span>
</p>

Example to demo the innerText and textContent properties


Now, let's select the two span elements and add the same text to them. This will help
you better understand the difference between innerText and textContent.
const example1 = document.querySelector('#inner-text');
const example2 = document.querySelector('#text-content');

let address = `
ABC Street,
Spintex Road,
Accra,
Ghana.
`;

example1.innerText = address;
example2.textContent = address;
The code gives the same variable address to the two examples. The first
uses innerText and the second uses textContent. See the results below:

Result of updating content with innerText and textContent.


Notice how innerText uses the line breaks but the textContent example doesn't.
Another key difference between the two methods is how they behave when used inside
loops. innerText can be slower than textContent when dealing with bulk operations or
frequent updates in a loop.

Conclusion
DOM manipulation in JavaScript is an important factor while creating a web application
using HTML and JavaScript. It is the process of interacting with the DOM API to change
or modify an HTML document that will be displayed in a web browser. This HTML
document can be changed to add or remove elements, update existing elements,
rearrange existing elements, etc.

By manipulating the DOM, we can create web applications that update the data in a web
page without refreshing the page and can change its layout without doing a refresh.
Throughout the document, items can be deleted, moved, or rearranged.

You might also like