The Fetch API
The Fetch API
Global scale on a startup budget. Built on Apache Cassandra™ in the cloud. Get $300
free credit.ADS VIA CARBON
Response Object
o Metadata
headers
status
statusText
url
o Body content
Request Object
Request headers
POST Requests
How to cancel a fetch request
Looking for more?
Introduction to the Fetch API
Since IE5 was released in 1998, we’ve had the option to make
asynchronous network calls in the browser
using XMLHttpRequest (XHR).
Quite a few years after this, GMail and other rich apps made heavy
use of it, and made the approach so popular that it had to have a
name: AJAX.
jQuery.ajax()
jQuery.get()
jQuery.post()
and so on.
Fetch has a good support across the major browsers, except IE.
The polyfill https://github.com/github/fetch released
by GitHub allows us to use fetch on any browser.
Using Fetch
Starting to use Fetch for GET requests is very simple:
fetch('/file.json')
Now let’s make this a bit more useful, let’s actually see what the
content of the file is:
fetch('./file.json')
.then(response => response.json())
.then(data => console.log(data))
Calling fetch() returns a promise. We can then wait for the
promise to resolve by passing a handler with the then() method
of the promise.
Catching errors
Since fetch() returns a promise, we can use the catch method of
the promise to intercept any error occurring during the execution
of the request, and the processing done in the then callbacks:
fetch('./file.json')
.then(response => {
//...
})
.catch(err => console.error(err))
fetch('./file.json')
.then(response => {
if (!response.ok) { throw
Error(response.statusText) }
return response
})
.then(response => {
//...
})
Response Object
The Response Object returned by a fetch() call contains all the
information about the request and the response of the network
request.
Metadata
headers
Accessing the headers property on the response object gives you
the ability to look into the HTTP headers returned by the request:
fetch('./file.json').then(response => {
console.log(response.headers.get('Content-Type'))
console.log(response.headers.get('Date'))
})
status
This property is an integer number representing the HTTP
response status.
fetch('./file.json').then(response =>
console.log(response.status))
statusText
statusText is a property representing the status message of the
response. If the request is successful, the status is OK.
fetch('./file.json').then(response =>
console.log(response.statusText))
url
url represents the full URL of the property that we fetched.
fetch('./file.json').then(response =>
console.log(response.url))
Body content
A response has a body, accessible using several methods:
fetch('./file.json')
.then(response => response.text())
.then(body => console.log(body))
fetch('./file.json')
.then(response => response.json())
.then(body => console.log(body))
Request Object
The Request object represents a resource request, and it’s usually
created using the new Request() API.
Example:
no-cache).
And exposes several methods
including json(), text() and formData() to process the body of
the request.
The full API can be found
at https://developer.mozilla.org/docs/Web/API/Request
Request headers
Being able to set the HTTP request header is essential,
and fetch gives us the ability to do this using the Headers object:
or:
Instead of:
fetch('./file.json')
we do
The Headers object is not limited to setting value, but we can also
query it:
headers.has('Content-Type')
headers.get('Content-Type')
headers.delete('X-My-Custom-Header')
POST Requests
Fetch also allows to use any other HTTP method in your request:
POST, PUT, DELETE or OPTIONS.
const options = {
method: 'post',
headers: {
'Content-type': 'application/x-www-form-
urlencoded; charset=UTF-8'
},
body: 'name=Flavio&test=1'
}
fetch('./file.json', { signal })
You can set a timeout that fires an abort event 5 seconds after the
fetch request has started, to cancel it:
When an abort signal occurs, fetch will reject the promise with
a DOMException named AbortError:
fetch('./file.json', { signal })
.then(response => response.text())
.then(text => console.log(text))
.catch(err => {
if (err.name === 'AbortError') {
console.error('Fetch aborted')
} else {
console.error('Another error', err)
}
})
XMLHttpRequest
(XHR)
The introduction of XMLHttpRequest (XHR) in browsers
in the mid 2000's was a huge win for the Web Platform.
Let's see how it works.
Published Apr 05 2018
Your new development career awaits. Check out the latest listings.ADS VIA CARBON
Introduction
An example XHR request
Additional open() parameters
onreadystatechange
Aborting an XHR request
Comparison with jQuery
Comparison with Fetch
Cross Domain Requests
Uploading files using XHR
Introduction
The introduction of XMLHttpRequest (XHR) in browsers in the mid
2000’s was a huge win for the Web Platform. Let’s see how it
works.
Things that now look normal, back in the day, looked like they
were coming from the future. I’m talking about GMail or Google
Maps, for example, which were all based in great part on XHR.
fetch('https://yoursite.com')
.then(data => {
console.log(data)
})
.catch(err => {
console.error(err)
})
Esakkimuthu E
Follow
Oct 27, 2019 · 9 min read
Here’s a list of concepts that are most often used when talking
about object-oriented programming (OOP):
Class
Encapsulation
Abstraction
Reusability/inheritance
Polymorphism
Association
Aggregation
Composition
After creating an object you can get the value with dot
notation. For example, we can get the value of the title
with book.title. We can also access the properties with square
brackets: book[‘title’].
Object constructor
Object.create()
Class
Class is not an object — it is the blueprint of an object. Classes
are special functions. You can define functions using function
expressions and declarations and you can define classes that
way as well. We can create the number of objects using the
blueprint.
You can use the class keyword and the name of the class. The
syntax is similar to that of Java.
Class syntax is a nice way to use object-oriented programming
and managing prototypes:
let Book = function(name) {
this.name = name
}let newBook = function(name) {
Book.call(this, name)
} newBook.prototype = Object.create(Book.prototype);
const book1 = new newBook("The Alchemist");
Encapsulation
Encapsulation means hiding information or data. It refers to
the ability of the object to execute its functionality without
revealing any execution details to the caller. In other words,
the private variable is only visible to the current function and
is not accessible to the global scope or other functions.
const Book = function(t, a) {
let title = t;
let author = a;
return {
summary : function() {
console.log(`${title} written by ${author}.`);
}
}
}
const book1 = new Book('Hippie', 'Paulo
Coelho');book1.summary();
> Hippie written by Paulo Coelho.
In the above code the title and the author are only visible
inside the scope of the function Book and the method summary is
visible to the caller of Book. So the title and the author are
encapsulated inside Book.
Abstraction
Abstraction means implementation hiding. It is a way of
hiding the implementation details and only showing the
essential features to the caller. In other words, it hides
irrelevant details and shows only what’s necessary to the outer
world. A lack of abstraction will lead to problems of code
maintainability.
const Book = function(getTitle, getAuthor) {
// Private variables / properties
let title = getTitle;
let author = getAuthor;// Public method
this.giveTitle = function() {
return title;
}
// Private method
const summary = function() {
return `${title} written by ${author}.`
}// Public method that has access to private method.
this.giveSummary = function() {
return summary()
}
}const book1 = new Book('Hippie', 'Paulo
Coelho');book1.giveTitle();
> "Hippie"book1.summary();
> Uncaught TypeError: book1.summary is not a
functionbook1.giveSummary();
> "Hippie written by Paulo Coelho."
Reusability/Inheritance
JavaScript inheritance is a mechanism allows us to create a
new class using the existing class. It means the child class
inherits all the properties and behaviors of the parent class.
Prototypal inheritance
For each instance of Book, we’re recreating the memory for the
methods from the base class. These methods must be shared
across all instances — they should not be specific to the
instance. Here the prototype comes into the picture:
let Corebook = function(title) {
this.title = title
}Corebook.prototype.title = function() {
console.log(`name of the book is ${this.title}`);
}Corebook.prototype.summary = function(author) {
console.log(`${this.title} is written by ${this.author}`);
}let Book = function(title, author) {
Corebook.call(this, title, author)
}Book.prototype = Object.create(Corebook.prototype);let book1 =
new Book('The Alchemist', 'Paulo Coelho');book1.title();
> name of the book is The Alchemistbook1.summary();
> The Alchemist is written by Paulo Coelho
Polymorphism
The ability to call the same method on different objects and
have each of them respond in their own way is called
polymorphism.
let book1 = function () {}
book1.prototype.summary = function() {
return "summary of book1"
}let book2 = function() {}
book2.prototype = Object.create(book1.prototype);
book2.prototype.summary = function() {
return "summary of book2"
}let book3 = function() {}
book3.prototype = Object.create(book1.prototype);
book3.prototype.summary = function() {
return "summary of book3"
}
Association
Association is the relationship between two or more objects.
Each Object is independent. In other words, association
defines the multiplicity between objects: one-to-one, one-to-
many, many-to-one, many-to-many.
Composition
Composition is a special case of aggregation. Composition is
when an object contains another object and the contained
object can’t live without the container object.
let Book = {
"title": "The Alchemist",
"author": "Paulo Coelho",
"publication": {
"name": "new publication Inc",
"address": "chennai"
}
}
JavaScript DOM
This section covers the JavaScript Document Object Model (DOM) and shows you
how to manipulate DOM elements effectively.
The DOM represents a document as a tree of nodes. It provides API that allows you
to add, remove, and modify parts of the document effectively.
<html>
<head>
<title>JavaScript DOM</title>
</head>
<body>
<p>Hello DOM!</p>
</body>
</html>
Code language: HTML, XML (xml)
Each document can have only one document element. In an HTML document, the
document element is the <html> element. Each markup can be represented by a
node in the tree.
Node Types
Each node in the DOM tree is identified by a node type. JavaScript uses integer
numbers to determine the node types.
Node.DOCUMENT_NODE 9 A Document node.
Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node.
node.nodeType
Code language: CSS (css)
You can compare the nodeType property with the above constants to determine the
node type. For example:
if (node.nodeType == Node.ELEMENT_NODE) {
// node is the element node
}
Code language: JavaScript (javascript)
The nodeName and nodeValue properties
The values of these properites depends on the node type. For example, if the node
type is the element node, the nodeName is always the same as element’s tag name
and nodeValue is always null.
For this reason, it’s better to test node type before using these properties:
if (node.nodeType == Node.ELEMENT_NODE) {
let name = node.nodeName; // tag name like <p>
}
Code language: JavaScript (javascript)
A node is a generic name of any object in the DOM tree. It can be any built-in DOM
element such as the document. Or it can be any HTML tag specified in the HTML
document like <div> or <p>.
In other words, the node is generic type of the element. The element is a specific
type of the node with the node type Node.ELEMENT_NODE.
Node Relationships
Any node has relationships to other nodes in the DOM tree. The relationships are
the same as the one described in a traditional family tree.
Summary
An HTML or XML document can be represented as a tree of nodes, like a
traditional family tree.
Each markup can be represented as a node with a specific node type.
Element is a specific type of node with the node type Node.ELEMENT_NODE.
In the DOM tree, a node has relationships with other nodes.
JavaScript getElementById
Introduction to JavaScript getElementById() method
An HTML element often has an id attribute like this:
<div id="root"></div>
Code language: HTML, XML (xml)
The id is used to uniquely identify an HTML element within the document. By rules,
the id root is unique within the document; no other elements can have this root id.
In this syntax, the id represents the id of the element that you want to select.
<html>
<head>
<title>JavaScript getElementById() Method</title>
</head>
<body>
<p id="message">A paragraph</p>
</body>
</html>
Code language: HTML, XML (xml)
const p = document.getElementById('message');
console.log(p);
Code language: JavaScript (javascript)
Output:
Once you selected an element, you can add styles to the element, manipulate
its attributes, and traversing to parent and child elements.
Summary
The getElementById() returns a DOM element specified by an id or null if no
matching element found.
If multiple elements share the same id, even though it is invalid,
the getElementById() returns the first element it encounters.
JavaScript getElementsByName
Introduction to JavaScript getElementsByName()
method
Every element on an HTML document may have a name attribute:
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.
When you click the Rate button, the page will show an alert dialog that displays
the rating of the service such as Very Poor, Poor, OK, Good, and Very Good:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript getElementsByName Demo</title>
</head>
<body>
<p>Please rate the service:</p>
<p>
<input type="radio" name="rate" value="Very poor">
Very poor
<input type="radio" name="rate" value="Poor"> Poor
<input type="radio" name="rate" value="OK"> OK
<input type="radio" name="rate" value="Good"> Good
<input type="radio" name="rate" value="Very Good">
Very Good
</p>
<p>
<button id="btnRate">Submit</button>
</p>
<script>
let btn = document.getElementById('btnRate');
btn.addEventListener('click', () => {
let rates = document.getElementsByName('rate');
rates.forEach((rate) => {
if (rate.checked) {
alert(`You rated: ${rate.value}`);
}
})
});
</script>
</body>
</html>
Code language: HTML, XML (xml)
How it works:
Notice that you will learn about events like click later. For now, you just need to
focus on the getElementsByName() method.
Summary
The getElementsByName() returns a live NodeList of elements with a specified
name.
The NodeList is an array-like object, not an array object.
JavaScript getElementsByTagName
Introduction to JavaScript getElementsByTagName() method
The getElementsByTagName() is a method of the document object or a specific DOM
element.
JavaScript getElementsByTagName() example
The following example illustrates how to use the getElementsByTagName() method to
get the number of H2 tags in the document.
When you click the Count H2 button, the page shows the number of H2 tags:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript getElementsByTagName() Demo</title>
</head>
<body>
<h1>JavaScript getElementsByTagName() Demo</h1>
<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>
<script>
let btn = document.getElementById('btnCount');
btn.addEventListener('click', () => {
let headings =
document.getElementsByTagName('h2');
alert(`The number of H2 tags: $
{headings.length}`);
});
</script>
</body>
</html>
Code language: HTML, XML (xml)
How it works:
Summary
The getElementsByTagName() is a method of the document or element object.
The getElementsByTagName() accepts a tag name and returns a list of elements
with the matching tag name.
The getElementsByTagName() returns a live HTMLCollection of elements.
The HTMLCollection is an array-like object.
JavaScript getElementsByClassName
Introduction to the getElementsByClassName() method
Every HTML element has an optional class attribute like this:
The value of the class attribute is a space-separated list of the classes of the
element. The classes are case-sensitive.
The classes allows you to use the CSS to match elements. For example:
.btn {
background-color: red;
}
Code language: CSS (css)
If you match elements by multiple classes, you need to use whitespace to separate
them like this:
<div id="app">
<header>
<nav>
<ul id="menu">
<li class="item">HTML</li>
<li class="item">CSS</li>
<li class="item highlight">JavaScript</li>
<li class="item">TypeScript</li>
</ul>
</nav>
<h1>getElementsByClassName Demo</h1>
</header>
<section>
<article>
<h2 class="heading-secondary">Example 1</h2>
</article>
<article>
<h2 class="heading-secondary">Example 2</h2>
</article>
</section>
</div>
Code language: HTML, XML (xml)
console.log(data);
Code language: JavaScript (javascript)
Output:
How it works:
First, select the <ul> element with the class name menu using
the getElementById() method.
Then, select <li> elements, which are the descendants of the <ul> element,
using the getElementsByClassName() method.
Finally, create an array of the text content of <li> elements by borrowing
the map() method of the Array object.
To search for the element with the class heading-secondary, you use the following code:
console.log(data);
Code language: JavaScript (javascript)
Output:
JavaScript querySelector
Introduction to JavaScript querySelector() and
querySelectorAll() methods
The querySelector() is a method of the Element interface. The querySelector() allows you to
find the first element that matches one or more CSS selectors.
You can call the querySelector() method on the document or any HTML element.
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.
let nodeList =
Array.from(document.querySelectorAll(selector));
Code language: JavaScript (javascript)
<!DOCTYPE html>
<html lang="en">
<head>
<title>querySelector() Demo</title>
</head>
<body>
<header>
<div id="logo">
<img src="img/logo.jpg" alt="Logo" id="logo">
</div>
<nav class="primary-nav">
<ul>
<li class="menu-item current"><a
href="#home">Home</a></li>
<li class="menu-item"><a
href="#services">Services</a></li>
<li class="menu-item"><a
href="#about">About</a></li>
<li class="menu-item"><a
href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<h1>Welcome to the JS Dev Agency</h1>
<div class="container">
<section class="section-a">
<h2>UI/UX</h2>
<p>Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Autem placeat, atque accusamus voluptas
laudantium facilis iure adipisci ab
veritatis eos neque culpa id nostrum tempora tempore minima.
Adipisci, obcaecati repellat.</p>
<button>Read More</button>
</section>
<section class="section-b">
<h2>PWA Development</h2>
<p>Lorem ipsum dolor sit, amet consectetur
adipisicing elit. Magni fugiat similique illo nobis quibusdam
commodi aspernatur, tempora doloribus
quod, consectetur deserunt, facilis natus optio. Iure
provident labore nihil in earum.</p>
<button>Read More</button>
</section>
<section class="section-c">
<h2>Mobile App Dev</h2>
<p>Lorem ipsum dolor sit amet consectetur
adipisicing elit. Animi eos culpa laudantium consequatur ea!
Quibusdam, iure obcaecati. Adipisci
deserunt, alias repellat eligendi odit labore! Fugit iste sit
laborum debitis eos?</p>
<button>Read More</button>
</section>
</div>
</main>
<script src="js/main.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
1) Universal selector
The universal selector denoted by * that matches all elements of any type:
2) Type selector
To select elements by node name, you use the type selector e.g., a selects
all <a> elements:
elementName
3) Class selector
To find the element with a given class attribute, you use the class selector syntax:
.className
Code language: CSS (css)
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:
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:
Grouping selectors
To group multiple selectors, you use the following syntax:
The selector list will match any element with one of the selectors in the group.
Combinators
1) descendant combinator
selector selector
2) Child combinator
The > child combinator finds all elements that are direct children of the first
element:
The following example finds all li elements that are directly inside a <ul> element:
selector ~ selector
selector + selector
Pseudo
1) Pseudo-classes
element:state
Code language: CSS (css)
2) Pseudo-elements
Summary
The querySelector() finds the first element that matches a CSS selector or a
group of CSS selectors.
The querySelectorAll() finds all elements that match a CSS selector or a group of
CSS selectors.
A CSS selector defines elements to which a CSS rule applies.
The parentNode is read-only.
If you create a new node but haven’t attached it to the DOM tree, the parentNode of
that node will also be null.
JavaScript parentNode example
See the following HTML document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript parentNode</title>
</head>
<body>
<div id="main">
<p class="note">This is a note!</p>
</div>
<script>
let note = document.querySelector('.note');
console.log(note.parentNode);
</script>
</body>
</html>
Code language: HTML, XML (xml)
How it works:
Summary
The node.parentNode returns the read-only parent node of a specified node
or null if it does not exist.
The document and DocumentFragment do not have a parent node.
JavasScript Siblings
Summary: in this tutorial, you will learn how to select the next siblings, previous
siblings, and all siblings of an element. Let’s say you have the following list of items:
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li>About Us</li>
</ul>
Code language: HTML, XML (xml)
Output:
<li>Careers</li>
Code language: HTML, XML (xml)
In this example:
To get all the next siblings of an element, you can use the following code:
let current = document.querySelector('.current');
let nextSibling = current.nextElementSibling;
while(nextSibling) {
console.log(nextSibling);
nextSibling = nextSibling.nextElementSibling;
}
Code language: JavaScript (javascript)
And the following example selects all the previous siblings of the list item that has
the current class:
First, select the parent of the element whose siblings that you want to find.
Second, select the first child element of that parent element.
Third, add the first element to an array of siblings.
Fourth, select the next sibling of the first element.
Finally, repeat the 3rd and 4th steps until there are no siblings left. In case
the sibling is the original element, skip the 3rd step.
// collecting siblings
while (sibling) {
if (sibling.nodeType === 1 && sibling !== e) {
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
};
Code language: JavaScript (javascript)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Siblings</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li>About Us</li>
</ul>
<script>
let getSiblings = function (e) {
// for collecting siblings
let siblings = [];
// if no parent, return no sibling
if(!e.parentNode) {
return siblings;
}
// first child of the parent node
let sibling = e.parentNode.firstChild;
// collecting siblings
while (sibling) {
if (sibling.nodeType === 1 && sibling !== e)
{
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
};
let siblings =
getSiblings(document.querySelector('.current'));
siblingText = siblings.map(e => e.innerHTML);
console.log(siblingText);
</script>
</body>
</html>
Code language: HTML, XML (xml)
Output:
Summary
The nextElementSibling returns the next sibling of an element or null if the
element is the last one in the list.
The previousElementSibling returns the previous sibling of an element or null if
the element is the first one in the list.
To get all siblings of an element, you can use a helper function that utilizes
the nextElementSibling property.
Getting Child Elements of a Node in
JavaScript
Summary: in this tutorial, you will learn how to get the first child element, last child
element, and all children of a specified element.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Child Elements</title>
</head>
<body>
<ul id="menu">
<li class="first">Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li class="last">About Us</li>
</ul>
</body>
</html>
Code language: HTML, XML (xml)
Output:
#text
Code language: CSS (css)
Note that any whitespace such as a single space, multiple spaces, returns, and tabs
will create a #text node. To remove the #text node, you can remove the whitespaces
as follows:
<article id="content"><h2>Heading</h2><p>First
paragraph</p></article>
Code language: HTML, XML (xml)
Or to get the first child with the Element node only, you can use
the firstElementChild property:
The following code returns the first list item which is the first child element of the
menu:
Output:
<li class="first">Home</li>
Code language: HTML, XML (xml)
In this example:
First, select the #menu element by using the getElementById() method.
Second, get the first child element by using the firstElementChild property.
The following code returns the list item which is the last child element of the menu:
Output:
The childNodes property returns all child elements with any node type. To get the
child element with only the element node type, you use the children property:
The following example selects all child elements of the element with the Id main:
let menu = document.getElementById('menu');
let children = menu.children;
console.log(children);
Code language: JavaScript (javascript)
Output:
Summary
The firstChild and lastChild return the first and last child of a node, which can be
any node type including text node, comment node, and element node.
The firstElementChild and lastElementChild return the first and last child Element
node.
The childNodes returns a live NodeList of all child nodes of any node type of a
specified node. The children return all child Element nodes of a specified
node.
JavaScript CreateElement
Summary: in this tutorial, you will learn how to use the
JavaScript document.createElement() to create a new HTML element and attach it to the
DOM tree.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS CreateElement Demo</title>
</head>
<body>
</body>
</html>
Code language: HTML, XML (xml)
document.body.appendChild(div);
Code language: CSS (css)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS CreateElement Demo</title>
</head>
<body>
<script>
let div = document.createElement('div');
div.id = 'content';
div.innerHTML = '<p>CreateElement example</p>';
document.body.appendChild(div);
</script>
</body>
</html>
Code language: HTML, XML (xml)
If you want to add an id to a div, you set the id attribute of the element to a value,
like this:
document.body.appendChild(div);
Code language: JavaScript (javascript)
document.body.appendChild(div);
Code language: JavaScript (javascript)
To add a piece of text to a <div>, you can use the innerHTML property as the above
example, or create a new Text node and append it to the div:
<ul id="menu">
<li>Home</li>
</ul>
Code language: HTML, XML (xml)
let li = document.createElement('li');
li.textContent = 'Products';
menu.appendChild(li);
li = document.createElement('li');
li.textContent = 'About Us';
Output:
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>
Code language: HTML, XML (xml)
You can first create a new helper function that loads a JavaScript file from an URL:
function loadJS(url) {
let script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
Code language: JavaScript (javascript)
loadJS('/lib.js');
Code language: JavaScript (javascript)
function loadJSAsync(url) {
let script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
}
Code language: JavaScript (javascript)
Summary
The document.createElement() creates a new HTML element.
The element.appendChild() appends an HTML element to an existing element.
JavaScript appendChild
Summary: in this tutorial, you will learn how to use the
JavaScript appendChild() method to add a node to the end of the list of child nodes of
a specified parent node.
parentNode.appendChild(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.
JavaScript appendChild() examples
Let’s take some examples of using the appendChild() method.
1) Simple appendChild() example
<ul id="menu">
</ul>
Code language: HTML, XML (xml)
function createMenuItem(name) {
let li = document.createElement('li');
li.textContent = name;
return li;
}
// get the ul#menu
const menu = document.querySelector('#menu');
// add menu item
menu.appendChild(createMenuItem('Home'));
menu.appendChild(createMenuItem('Services'));
menu.appendChild(createMenuItem('About Us'));
Code language: JavaScript (javascript)
How it works:
Output:
<ul id="menu">
<li>Home</li>
<li>Services</li>
<li>About Us</li>
</ul>
Code language: HTML, XML (xml)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript appendChild() Demo</title>
</head>
<body>
<ul id="menu">
</ul>
<script>
function createMenuItem(name) {
let li = document.createElement('li');
li.textContent = name;
return li;
}
// get the ul#menu
const menu = document.querySelector('#menu');
// add menu item
menu.appendChild(createMenuItem('Home'));
menu.appendChild(createMenuItem('Services'));
menu.appendChild(createMenuItem('About Us'));
</script>
</body>
</html>
Code language: HTML, XML (xml)
<ul id="first-list">
<li>Everest</li>
<li>Fuji</li>
<li>Kilimanjaro</li>
</ul>
<ul id="second-list">
<li>Karakoram Range</li>
<li>Denali</li>
<li>Mont Blanc</li>
</ul>
Code language: HTML, XML (xml)
The following example uses the appendChild() to move the first child element from
the first list to the second list:
How it works:
Summary
Use appendChild() method to add a node to the end of the list of child nodes
of a specified parent node.
The appendChild() can be used to move an existing child node to the new
position within the document.
JavaScript textContent
Summary: in this tutorial, you will learn how to use the
JavaScript textContent property to get the text content of a node and its descendants.
Reading textContent from a node
To get the text content of a node and its descendants, you use
the textContent property:
<div id="note">
JavaScript textContent Demo!
<span style="display:none">Hidden Text!</span>
<!-- my comment -->
</div>
Code language: HTML, XML (xml)
How it works.
Output:
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:
Output:
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 brower 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:
node.textContent = 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:
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.
When you read the innerHTML of an element, the web browser has to serialize the
HTML fragment of the element’s descendants.
1) Simple innerHTML example
<ul id="menu">
<li>Home</li>
<li>Services</li>
</ul>
Code language: HTML, XML (xml)
How it works:
Output:
<li>Home</li>
<li>Services</li>
Code language: HTML, XML (xml)
<!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 = document.getElementById('menu');
console.log(menu.innerHTML);
</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.
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
contents of the document.body element:
document.body.innerHTML = '';
Code language: JavaScript (javascript)
⚠️Security Risk
HTML5 specifies that a <script> tag inserted with innerHTML should not execute.
See the following example:
index.html document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript innerHTML</title>
</head>
<body>
<div id="main"></div>
<script src="app.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
app.js
Therefore, you should not set the innerHTML to the content that you have no control
over or you will face a potential security risk.
Because of this, if you want to insert plain text into the document, you use
the textContent property instead of the innerHTML. The textContent will not be parsed as
the HTML, but as the raw text.
Summary
Use innerHTML property of an element to get or set HTML contained within
the element.
The innerHTML property returns the current HTML source of the element,
including any change that has been made since the page was loaded.
Do not use innerHTML to set new content that you have no control over to
avoid a security risk.
<div class="container"></div>
Code language: HTML, XML (xml)
If you set the contents that you have no control over to the innerHTML, the
malicious code may be injected and executed.
A document fragment does not link to the active DOM tree, therefore, it
doesn’t incur any performance.
JavaScript DocumentFragment
Summary: in this tutorial, you’ll learn about the JavaScript DocumentFragment interface
to compose DOM nodes and update them to the active DOM tree.
Introduction to the JavaScript DocumentFragment
interface
The DocumentFragment interface is a lightweight version of the Document that stores a
piece of document structure like a standard document. However,
a DocumentFragment isn’t part of the active DOM tree.
If you make changes to the document fragment, it doesn’t affect the document or
incurs any performance.
The following code creates a list of <li> elements (<li>) and append each to
the <ul> element using the DocumentFragment:
langEl.appendChild(fragment);
Code language: JavaScript (javascript)
How it works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>DocumentFragment Demo</title>
</head>
<body>
<ul id="language"></ul>
<script>
let languages = ['JS', 'TypeScript', 'Elm', 'Dart',
'Scala'];
let langEl = document.querySelector('#language');
let fragment = new DocumentFragment();
languages.forEach((language) => {
let li = document.createElement('li');
li.innerHTML = language;
fragment.appendChild(li);
})
langEl.appendChild(fragment);
</script>
</body>
</html>
Code language: HTML, XML (xml)
Summary
Use the DocumentFragment to compose DOM nodes before updating them to
the active DOM tree to get better performance.
JavaScript insertBefore
Summary: in this tutorial, you will learn how to use the JavaScript insertBefore() to
insert a node before another node as a child node of a specified parent node.
Introduction to JavaScript insertBefore() method
To insert a node before another node as a child node of a parent node, you use
the parentNode.insertBefore() method:
parentNode.insertBefore(newNode, existingNode);
Code language: CSS (css)
In this method:
JavaScript insertBefore() helper function
The following insertBefore() function inserts a new node before a specified node:
JavaScript insertBefore() example
Suppose that you have the following list of items:
<ul id="menu">
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>
Code language: HTML, XML (xml)
The following example uses the insertBefore() method to insert a new node as the first
list item:
How it works.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript insertBefore()</title>
</head>
<body>
<ul id="menu">
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
let menu = document.getElementById('menu');
// create a new li node
let li = document.createElement('li');
li.textContent = 'Home';
</html>
Code language: HTML, XML (xml)
Summary
Use the parentNode.insertBefore() to insert a new node before an existing node as
a child node of a parent node.
JavaScript insertAfter
Summary: in this tutorial, you will learn how to insert a new node after an existing
node as a child node of a parent node.
JavaScript DOM provides the insertBefore() method that allows you to insert a new
after an existing node as a child node. However, it hasn’t supported
the insertAfter() method yet.
To insert a new node after an existing node as a child node, you can use the
following approach:
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
Code language: HTML, XML (xml)
The following snippet inserts a new node after the first list item:
How it works:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript insertAfter() Demo</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
let menu = document.getElementById('menu');
// create a new li node
let li = document.createElement('li');
li.textContent = 'Services';
</html>
Code language: HTML, XML (xml)
Summary
JavaScript DOM hasn’t supported the insertAfter() method yet.
Use the insertBefore() method and the nextSibling property to insert a new before
an existing node as a child of a parent node.
https://www.javascripttutorial.net/javascript-dom/javascript-insertadjacenthtml/