0% found this document useful (0 votes)
5 views29 pages

JavaScript DOM Manipulation Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views29 pages

JavaScript DOM Manipulation Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Document Object Model in JavaScript

Suppose you have an HTML file called [Link] with the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,
initial-scale=1.0" />
<title>JavaScript DOM</title>
</head>
<body>
<h1>Hello DOM!</h1>
</body>
</html>
Code language: HTML, XML (xml)

If you open the [Link] on your web browser, you’ll see the following
page.
The web browser displays the message Hello DOM! as specified by the
<h1> tag on the [Link] document.

Additionally, the web browser also creates something called a DOM tree
internally:

DOM stands for document object model.

The web browser uses DOM to represent the HTML document internally.
Additionally, it provides a set of functions and methods to modify the HTML
document programmatically.
These functions and methods are often called DOM Application Programming
Interfaces or DOM API.

For example, you can use JavaScript to select the h1 tag using the
querySelector() method:

const h1 = [Link]('h1');
Code language: JavaScript (javascript)

And you can get the text content of the h1 element:

[Link]([Link])
Code language: CSS (css)

It’ll show the text content of the h1 tag in the console:

Hello DOM!

You can change the h1 tag dynamically by setting the textContent to a new
text:

[Link] = 'Hi JS';


Code language: JavaScript (javascript)

Using DOM API in JavaScript, you can manipulate the HTML document
effectively.

In the next tutorials, you’ll learn various methods for selecting, traversing, and
manipulating DOM.
Summary

●​ DOM stands for Document Object Model.


●​ DOM API provides a set of functions and methods to modify the HTML
document dynamically via JavaScript.

getElementById()

The getElementById() method of the document object returns an HTML


element with the specified id.

Here’s the syntax of the getElementById() method:

const element = [Link](id);


Code language: JavaScript (javascript)

In this syntax:

●​ id is a string that represents the id of the element to select.

JavaScript getElementById() method example

Suppose you have a document with two p elements:

<p id="first">Hi, There!</p>


<p>JavaScript is fun.</p>
Code language: HTML, XML (xml)
The following code shows how to get the element with the id first:

const elem = [Link]("first");


Code language: JavaScript (javascript)

getElementsByName() method

Every element on an HTML document may have a name attribute:

<input type="radio" name="language" value="JavaScript">


Code language: HTML, XML (xml)

Unlike the id attribute, multiple HTML elements can share the same value of
the name attribute like this:

<input type="radio" name="language" value="JavaScript">


<input type="radio" name="language" value="TypeScript">
Code language: HTML, XML (xml)

To get all elements with a specified name, you use the


getElementsByName() method of the document object:

let elements = [Link](name);


Code language: JavaScript (javascript)

The getElementsByName() accepts a name which is the value of the name


attribute of elements and returns a live NodeList of elements.
The return collection of elements is live. It means that the return elements are
automatically updated when elements with the same name are inserted
and/or removed from the document.

JavaScript getElementsByName() example

The following example shows a radio group that consists of radio buttons that
have the same name (rate).

When you select a radio button and click the submit button, the page will show
the selected value such as Very Poor, Poor, OK, Good, or Very Good:

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>JavaScript getElementsByName Demo</title>
</head>

<body>
<p>Please rate the service:</p>
<p>
<label for="very-poor">
<input type="radio" name="rate" value="Very
poor" id="very-poor"> Very poor
</label>
<label for="poor">
<input type="radio" name="rate" value="Poor"
id="poor"> Poor
</label>
<label for="ok">
<input type="radio" name="rate" value="OK"
id="ok"> OK
</label>
<label for="good">
<input type="radio" name="rate" value="Good">
Good
</label>
<label for="very-good">
<input type="radio" name="rate" value="Very
Good" id="very-good"> Very Good
</label>
</p>
<p>
<button id="btnRate">Submit</button>
</p>
<p id="output"></p>
<script>
let btn = [Link]('btnRate');
let output = [Link]('output');

[Link]('click', () => {
let rates =
[Link]('rate');
[Link]((rate) => {
if ([Link]) {
[Link] = `You selected:
${[Link]}`;
}
});

});
</script>
</body>

</html>
Code language: HTML, XML (xml)

How it works:

●​ First, select the submit button by its id btnRate using the


getElementById() method.
●​ Second, listen to the click event of the submit button.
●​ Third, get all the radio buttons using the getElementsByName() and
show the selected value in the output element.
getElementsByTagName() method

he getElementsByTagName() is a method of the document object or a


specific DOM element.

Here’s the syntax of the getElementsByTagName() method:

let elements = [Link](tagName);

<body>
<h2>First heading</h2>
<p>This is the first paragraph.</p>
<h2>Second heading</h2>
<p>This is the second paragraph.</p>
<h2>Third heading</h2>
<p>This is the third paragraph.</p>

<button id="btnCount">Count h2</button>

<script>
let btn = [Link]('btnCount');
[Link]('click', () => {
let headings = [Link]('h2');
alert(`The number of H2 tags: ${[Link]}`);
});
</script>
</body>
getElementsByClassName() method
The getElementsByClassName() method returns an HTMLCollection of
elements whose class names match one or more specified class names.

querySelector() and querySelectorAll() methods

The querySelector() is a method of the Element interface. The


querySelector() method allows you to select the first element that
matches one or more CSS selectors.

The following illustrates the syntax of the querySelector() method:

let element = [Link](selector);


Code language: JavaScript (javascript)

In this syntax, the selector is a CSS selector or a group of CSS selectors to


match the descendant elements of the parentNode.

If the selector is not valid CSS syntax, the method will raise a
SyntaxError exception.

If no element matches the CSS selectors, the querySelector() returns


null.

Besides the querySelector(), you can use the querySelectorAll()


method to select all elements that match a CSS selector or a group of CSS
selectors
Basic selectors
1) Universal Selector

The universal selector is denoted by * that matches all elements of any type:

The following example uses the querySelector() selects the first element
in the document:

let element = [Link]('*');


Code language: JavaScript (javascript)

And this selects all elements in the document:

let elements = [Link]('*');


Code language: JavaScript (javascript)
2) Type selector

To select elements by node name, you use the type selector e.g., a selects all
<a> elements:

elementName

The following example finds the first h1 element in the document:

let firstHeading = [Link]('h1');


Code language: JavaScript (javascript)

The following example finds all h2 elements:


let heading2 = [Link]('h2');
Code language: JavaScript (javascript)
3) Class selector

To find the element with a given CSS class, you use the class selector syntax:

.className
Code language: CSS (css)

The following example finds the first element with the menu-item class:

let note = [Link]('.menu-item');


Code language: JavaScript (javascript)

The following example finds all elements with the menu class:

let notes = [Link]('.menu-item');


Code language: JavaScript (javascript)
4) ID Selector

To select an element based on the value of its id, you use the id selector
syntax:

#id
Code language: CSS (css)

The following example finds the first element with the id #logo:

let logo = [Link]('#logo');


Code language: JavaScript (javascript)
Since the id should be unique in the document, the querySelectorAll()
is not relevant.

5) Attribute selector

To select all elements that have a given attribute, you use one of the following
attribute selector syntaxes:

[attribute]

[attribute=value]

[attribute~=value]

[attribute|=value]

[attribute^=value]

[attribute$=value]

[attribute*$*=value]

Code language: JSON / JSON with Comments (json)

The following example finds the first element with the attribute [autoplay]
with any value:

let autoplay = [Link]('[autoplay]');


Code language: JavaScript (javascript)
The following example finds all elements that have [autoplay] attribute
with any value:

let autoplays = [Link]('[autoplay]');


Code language: JavaScript (javascript)

Grouping selectors

To group multiple selectors, you use the following syntax:

selector, selector, ...

The selector list will match any element with one of the selectors in the group.

The following example finds all <div> and <p> elements:

let elements = [Link]('div, p');


Code language: JavaScript (javascript)

Combinators
1) descendant combinator

To find descendants of a node, you use the space ( ) descendant combinator


syntax:

selector selector

For example p a will match all <a> elements inside the p element:

let links = [Link]('p a');


Code language: JavaScript (javascript)
2) Child combinator

The > child combinator finds all elements that are direct children of the first
element:

selector > selector

The following example finds all li elements that are directly inside a <ul>
element:

let listItems = [Link]('ul > li');


Code language: JavaScript (javascript)

To select all li elements that are directly inside a <ul> element with the
class nav:

let listItems = [Link]('[Link] > li');


Code language: JavaScript (javascript)
3) General sibling combinator

The ~ combinator selects siblings that share the same parent:

selector ~ selector

For example, p ~ a will match all <a> elements that follow the p element,
immediately or not:

let links = [Link]('p ~ a');


Code language: JavaScript (javascript)
4) Adjacent sibling combinator
The + adjacent sibling combinator selects adjacent siblings:

selector + selector

For example, h1 + a matches all elements that directly follow an h1:

let links = [Link]('h1 + a');


Code language: JavaScript (javascript)

Select the first <a> that directly follows an h1:

let links = [Link]('h1 + a');


Code language: JavaScript (javascript)

Pseudo
1) Pseudo-classes

The : pseudo matches elements based on their states:

element:state
Code language: CSS (css)

For example, the li:nth-child(2) selects the second <li> element in a


list:

let listItem =
[Link]('li:nth-child(2)');
Code language: JavaScript (javascript)
2) Pseudo-elements
The :: represent entities that are not included in the document therefore the
querySelector() method cannot select pseudo-elements.

CreateElement() Method
To create an HTML element, you use the [Link]()
method:

let element = [Link](htmlTag);


Code language: JavaScript (javascript)

The [Link]() accepts an HTML tag name and returns


a new Node with the Element type.

1) Creating a new div example

Suppose that you have the following HTML document:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>JS CreateElement Demo</title>

</head>
<body>

</body>

</html>
Code language: HTML, XML (xml)

The following example uses the [Link]() to create a


new <div> element:

let div = [Link]('div');


Code language: JavaScript (javascript)

And add an HTML snippet to the div:

[Link] = '<p>CreateElement example</p>';


Code language: JavaScript (javascript)

To attach the div to the document, you use the appendChild() method:

[Link](div);

appendChild() method

The appendChild() is a method of the Node interface. The


appendChild() method allows you to add a node to the end of the list of
child nodes of a specified parent node.

The following illustrates the syntax of the appendChild() method:


[Link](childNode);
Code language: CSS (css)

In this method, the childNode is the node to append to the given parent
node. The appendChild() returns the appended child.

If the childNode is a reference to an existing node in the document, the


appendChild() method moves the childNode from its current position to
the new position.

JavaScript appendChild() method examples

Let’s take some examples of using the appendChild() method.

1) Basic appendChild() example

Suppose that you have the following HTML markup:

<ul id="menu">

</ul>
Code language: HTML, XML (xml)

The following example uses the appendChild() method to add three list
items to the <ul> element:

function createMenuItem(name) {

let li = [Link]('li');

[Link] = name;
return li;

// get the ul#menu

const menu = [Link]('#menu');

// add menu item

[Link](createMenuItem('Home'));

[Link](createMenuItem('Services'));

[Link](createMenuItem('About Us'));

Code language: JavaScript (javascript)

How it works:

●​ First, the createMenuItem() function creates a new list item element


with a specified name by using the createElement() method.
●​ Second, select the <ul> element with id menu using the
querySelector() method.
●​ Third, call the createMenuItem() function to create a new menu item
and use the appendChild() method to append the menu item to the
<ul> element

Output:
<ul id="menu">

<li>Home</li>

<li>Services</li>

<li>About Us</li>

</ul>

JavaScript textContent
Reading textContent from a node

To get the text content of a node and its descendants, you use the
textContent property:

let text = [Link];


Code language: JavaScript (javascript)

Suppose that you have the following HTML snippet:

<div id="note">
JavaScript textContent Demo!
<span style="display:none">Hidden Text!</span>
<!-- my comment -->
</div>
Code language: HTML, XML (xml)

The following example uses the textContent property to get the text of the
<div> element:

let note = [Link]('note');


[Link]([Link]);
Code language: JavaScript (javascript)

How it works.

●​ First, select the div element with the id note by using the
getElementById() method.
●​ Then, display the text of the node by accessing the textContent
property.

Output:

JavaScript textContent Demo!


Hidden Text!

As you can see clearly from the output, the textContent property returns
the concatenation of the textContent of every child node, excluding
comments (and also processing instructions).

textContent vs. innerText

On the other hand, the innerText takes the CSS style into account and
returns only human-readable text. For example:
let note = [Link]('note');
[Link]([Link]);
Code language: JavaScript (javascript)

Output:

JavaScript textContent Demo!

As you can see, the hidden text and comments are not returned.

Since the innerText property uses the up-to-date CSS to compute the text,
accessing it will trigger a reflow, which is computationally expensive.

A reflow occurs when a web browser needs to process and draw parts or all
of a webpage again.

Setting textContent for a node

Besides reading textContent, you can also use the textContent property
to set the text for a node:

[Link] = newText;

When you set textContent on a node, all the node’s children will be removed
and replaced by a single text node with the newText value. For example:

let note = [Link]('note');


[Link] = 'This is a note';
Code language: JavaScript (javascript)

Summary
●​ Use the textContent property to return the concatenation of the
textContent of every child node. You can use it to set a text for a
node.
●​ The innerText returns the human-readable text that takes CSS into
account.

JavaScript innerHTML

Summary: in this tutorial, you will learn how to use the JavaScript innerHTML
property of an element to get or set an HTML markup contained in the
element.

The innerHTML is a property of the Element that allows you to get or set the
HTML markup contained within the element:

[Link] = 'new content';


[Link];
Code language: JavaScript (javascript)

Reading the innerHTML property of an element

To get the HTML markup contained within an element, you use the following
syntax:

let content = [Link];


Code language: JavaScript (javascript)

When you read the innerHTML of an element, the web browser has to
serialize the HTML fragment of the element’s descendants.
1) Simple JavaScript innerHTML example

Suppose that you have the following markup:

<ul id="menu">
<li>Home</li>
<li>Services</li>
</ul>
Code language: HTML, XML (xml)

The following example uses the innerHTML property to get the content of the
<ul> element:

let menu = [Link]('menu');


[Link]([Link]);
Code language: JavaScript (javascript)

How it works:

●​ First, select the <ul> element by its id (menu) using the


getElementById() method.
●​ Then, get the HTML content of the <ul> element using the innerHTML.

Output:

<li>Home</li>
<li>Services</li>
Code language: HTML, XML (xml)
2) Examining the current HTML source
The innerHTML property returns the current HTML source of the document,
including all changes that have been made since the page was loaded.

See the following example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript innerHTML</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>Services</li>
</ul>
<script>
let menu = [Link]('menu');

// create new li element


let li = [Link]('li');
[Link] = 'About Us';

// add it to the ul element


[Link](li);
[Link]([Link]);
</script>
</body>
</html>
Code language: HTML, XML (xml)

Output:

<li>Home</li>
<li>Services</li>
<li>About Us</li>
Code language: HTML, XML (xml)

How it works.

●​ First, get the <ul> element with the id menu using the
getElementById() method.
●​ Second, create a new <li> element and add it to the <ul> element
using the createElement() and appendChild() methods.
●​ Third, get the HTML of the <ul> element using the innerHTML property
of the <ul> element. The contents of the <ul> element includes the
initial content and the dynamic content created dynamically by
JavaScript.

Setting the innerHTML property of an element

To set the value of innerHTML property, you use this syntax:


[Link] = newHTML;

The setting will replace the existing content of an element with the new
content.

For example, you can remove the entire contents of the document by clearing
the contents of the [Link] element:

[Link] = '';
Code language: JavaScript (javascript)

You might also like