This quick HTML Node guide will cover 21 of the most popular and widely used APIs in the HTML DOM Node:
Every developer should have these APIs at their fingertips before taking on web frameworks. Mastering them is the best way to build a foundational understanding of when and how to use the frameworks.
Let’s dive in.
getElementById(id)
getElementById(id)
returns the Node instance of an element by its id
attribute.
<div id="div1">Div 1</div> <p id="par1">I'm a Paragraph</p>
To get the DOM instance of 1
using the getElementById
method, pass its ID, div1
, to the method.
const div1Node = document.getElementById("div1")
div1Node
is an object or instance of HTMLDivElement
.
To get the DOM instance of I'm a Paragraph
, pass its ID, par1
.
const par1Node = document.getElementById("par1")
par1Node
is an object or instance of HTMLParagraphElement
.
With these instances, we can manipulate or perform actions on the elements.
getElementsByClassName(className)
This method returns a collection (HTMLCollection
) of DOM nodes whose attribute class
value is equal to the className
string.
<div class="tab-body"> <div class="tab-content tab-active"> Div 1 </div> <div class="tab-content"> Div 2 </div> <div class="tab-content"> Div 3 </div> </div>
We have divs with the attribute class
names tab-body
, tab-content
, and tab-active
. All of these are class names. A class name is the value of the class
attribute set on an element.
To get the DOM Nodes of the divs with class
name tab-content
, call the getElementsByClassName()
method by passing tab-content
as arg.
>> document.getElementsByClassName("tab-content") // HTMLCollection 0: <div class="tab-content tab-active"> 1: <div class="tab-content"> 2: <div class="tab-content"> length: 3
As you can see, it returns a collection of the divs. It is actually an array because we can refer to them using number-index
. As you might guess, the first element is Div 1
, the second element is Div 2
, and the third element is Div 3
.
getElementsByTagName(tagName)
This will return a collection of DOM nodes whose tag name(element name) is equal to the tagName
string specified.
The tag name will consist of names of the elements, such as div
, p
, img
, video
, b
, i
, br
, button
, input
, etc.
<div> Div 1 </div> <div> Div 2 </div> <p> I'm Paragraph 1 </p> <p> I'm Paragraph 2 </p> <button>Button 1</button> <button>Button 2</button>
If you call getElementsByTagName()
with arg
, it will return the divs in the HTML.
document.getElementsByTagName("div") // HTMLCollection 0: <div> Div 1 1: <div> Div 2 length: 2
Passing p
returns all paragraph elements.
document.getElementsByTagName("p") // HTMLCollection 0: <p> I'm Paragraph 1 1: <p> I'm Paragraph 2 length: 2
Passing button
returns all button elements.
document.getElementsByTagName("button") // HTMLCollection // 0: <button> Button 1 // 1: <button> Button 2 // length: 2
getSelection()
This method returns the text node of the text selected in a document. This selected text area is the area highlighted in the document using the mouse or by the finger in a touch screen.
This method returns Selection
. This object has an anchorNode
property whose value is the text node of the text highlighted.
<div>I'm Div1</div>
If you highlight I'm Div1
, document.getSlection()
will return the object.
document.getSelection() // Selection // anchorNode: #text // ...
The anchorNode
is a text node whose nodeValue
is Div1
, the highlighted text.
// TODO: Complete this.
getElementsByName
and querySelector(selector)
This method will return the first occurrence of the DOM node with the selector
string specified.
The selector
string could be an:
Let’s zoom in on each scenario.
The selector
will be the element’s name.
<div> Div 1 </div> <div> Div 2 </div> <div> Div 3 </div>
document.querySelector("div") >> div Div 1
It will return the first occurance of the div element — in this case, Div 1
.
To get by the element’s attribute class
name, the class name arg is prefixed with a dot .
.
<div class="tab div1"> Div 1 </div> <div class="tab div2"> Div 2 </div> <div class="div3"> Div 3 </div>
To get div with class div1
:
document.querySelector(".div1") >> div Div 1
We started with a dot (.
) and then the class name.
To get div with class div2
:
document.querySelector(".div2") >> div Div 2
If you pass .tab
, there are two divs with tab
class names. Only the first div is returned.
document.querySelector(".tab") >> div Div 1
To get an element with its IS name, prefix the ID name arg with a hash #
.
<div id="div1"> Div 1 </div> <div id="div2"> Div 2 </div> <div id="div3"> Div 3 </div>
To get the div with id “div1”:
document.querySelector("#div1")
Note the use of the hash #
. We started with the #
followed by the ID name.
This returns the divDiv 1
.
querySelectorAll(selector)
This will return the NodeList of all occurrences of the selector
in a document.
Again, the selector
could be an:
<div> Div 1 </div> <div> Div 2 </div> <div> Div 3 </div> <p> I'm Paragraph 1 </p> <p> I'm Paragraph 2 </p>
To select all divs, pass div
to the method.
document.querySelectorAll("div") // NodeList(3) // 0: div Div 1 // 1: div Div 2 // 2: div Div 3
It returns a NodeList
of all the divs. NodeList
is like an array, so you can refer to the elements by index.
Once again, the first element is Div 1
, the second is Div 2
, and the third is Div 3
.
Query the elements by their class names.
<div class="tab div1"> Div 1 </div> <div class="div2"> Div 2 </div> <p class="tab par1"> I'm Paragraph </p>
To query elements with the class name tab
, pass .tab
(a dot followed by the class name).
document.querySelectorAll(".tab") // NodeList(2) // 0: div Div 1 // 1: p I'm Paragraph
It returns the Div 1
and I'm Paragraph
elements because they have the class name tab
.
This queries elements with a specified id
attribute value. The arg starts with a hash (#
) followed immediately by the ID name.
In this case, id
s are unique. If you assign the same id
value to more than one element, the browser will take the first element and ignore the rest. Using getElementById
returns null on id
s with values assigned to multiple elements. But using this querySelectorAll
returns all the elements with the specified id
value.
<div class="div1" id="tab"> Div 1 </div> <div class="div2" id="tab"> Div 2 </div> <p class="tab par1" id="par1"> I'm Paragraph </p>
To get the elements with tab
id
s:
document.querySelectorAll("#tab") // NodeList(2) // 0: div Div 1 // 1: div Div 2
Div 1
and Div 2
are returned because they have the ID tab
.
parentNode.insertBefore(newNode, refNode)
This method places a Node before a child Node refNode
in a parentNode
. The newNode
is followed immediately by the refNode
, all are children of the parentNode
.
<div id="parent"> Parent Node <div id="child">Child Node</div> </div>
To place an element before the #child
, use the insertBefore
method.
const newNode = document.createElement("b") newNode.appendChild(document.createTextNode("Bold Child Node")) parent.insertBefore(newNode, child)
Here we created a b
bold element with text node Bold Child Node
and used the insertBefore
method to insert it before the #child
node in the #parent
.
The HTML looks like this:
<div id="parent"> Parent Node <b>Bold Child Node</b> <div id="child">Child Node</div> </div>
If you refer to an existing Node in the DOM, the Node will be removed from its position and placed in the new position.
<div> Other Node <div id="othernode"> Other Node Child </div> </div> <div id="parent"> Parent Node <div id="child">Child Node</div> </div>
We want to use insertBefore
to insert #othernode
to #parent
before its child #child
.
parent.insertBefore(othernode, child)
This removes #othernode
from its parent node Other Node
and places it inside #parent
before its #child node
.
The outcome:
<div> Other Node </div> <div id="parent"> Parent Node <div id="othernode"> Other Node Child </div> <div id="child">Child Node</div> </div>
appendChild(node)
This method adds a node to an element as its last child element.
<div id="divNode"> <div>Div Node Child</div> <div>Div Node Child</div> <p>Paragraph Node Child</p> </div>
To append a p
element to the #divNode
using appendChild
:
const pEl = document.createElement("p") pEl.append(createTextNode("Paragraph Node Child")) divNode.appendChild(pEl)
The outcome:
<div id="divNode"> <div>Div Node Child</div> <div>Div Node Child</div> <p>Paragraph Node Child</p> <p>Paragraph Node Child</p> </div>
A new p
Node is added to the end of the #divNode
.
If the node is an existing node in the document, it will be removed from its position.
<p id="pNode">Paragraph Node</p> <div id="divNode"> <div>Div Node Child</div> <div>Div Node Child</div> <p>Div Node Child</p> </div>
Appending p#pNode
to #divNode
will remove p#pNode
from its original position.
divNode.appendChild(pNode)
The outcome:
<div id="divNode"> <div>Div Node Child</div> <div>Div Node Child</div> <p>Div Node Child</p> <p id="pNode">Paragraph Node</p> </div>
createElement(elementName)
This method creates the Node of the element specified. The elementName
arg is a string value of the element Node to be created.
To create a div Nod, pass div
. A button node will be "button"
, etc.
const divNode = document.createElement("div") const buttonNode = document.createElement("button")
divNode
will be an HTMLDivElement
object. buttonNode
will be an HTMLButtonElement
object.
All element nodes created from this have a base inheritance from HTMLElement
.
divNode instanceof HTMLDivElement >> true divNode instanceof HTMLElement >> true buttonNode instanceof HTMLButtonElement >> true buttonNode instanceof HTMLElement >> true
The element nodes returned are used to manipulate and perform actions on the node and its children.
createTextNode(textString)
This method creates a Text node. A Text node is used to represent a place in the DOM or element where text will be placed.
To place text in an element, you must first create a Text node by calling createTextNode
with the text string as arg and then appending the text node to the element.
<div id="parentNode"> <div>Child Node</div> </div>
To place a text in #parentNode
:
parentNode.appendChild(document.createTextNode("Text"))
The outcome:
<div id="parentNode"> <div>Child Node</div> Text </div>
removeChild(childNode)
This removes a child node and its children from a node.
<div id="parentNode"> <div id="childNode1">Child Node 1</div> <div id="childNode2">Child Node 2</div> <div id="childNode3">Child Node 3</div> </div>
To remove #childNode1
from #parentNode
:
parentNode.removeChild(childNode1)
The outcome:
<div id="parentNode"> <div id="childNode2">Child Node 2</div> <div id="childNode3">Child Node 3</div> </div>
The node to be removed must be a child node of the reference node. Trying to remove a node that is not a child of the specified node will throw a NotFoundError
.
NotFoundError: Node.removeChild: The node to be removed is not a child of this node
Trying to remove something that is nonexistent will throw ReferenceError
.
ReferenceError: childNode11 is not defined
replaceChild(newNode, childNode)
This method replaces a child node in a parent node with the specified node.
The newNode
is the node to replace the chidlNode
of the parent node.
The newNode
to replace the childNode
can be a child node of the parent node.
<div id="node">Node 1</div> <div id="parentNode"> <div id="childNode2">Child Node 2</div> <div id="childNode3">Child Node 3</div> </div>
To replace #childNode2
in #parentNode
with #node
:
parentNode.replaceChild(node, childNode2)
The outcome:
<div id="parentNode"> <div id="node">Node 1</div> <div id="childNode3">Child Node 3</div> </div>
#node
is removed from its original position and replaced with the #childNode2
in its position inside the #parent
.
<div id="parentNode"> <div id="childNode1">Child Node 1</div> <div id="childNode2">Child Node 2</div> <div id="childNode3">Child Node 3</div> </div>
You can replace #childNode2
with #childNode1
.
parentNode.replaceChild(childNode1, childNode2)
The outcome:
<div id="parentNode"> <div id="childNode1">Child Node 1</div> <div id="childNode3">Child Node 3</div> </div>
setAttribute(attrKey, attrValue)
This method sets an attribute to an element. attrKey
is the attribute name and attrValue
is the value of the attribute.
<div id="divNode">Div </div>
To set a class
attribute to #divNode
with a value of panel
using setAttribute
:
divNode.setAttribute("class", "panel")
The outcome will be:
<div id="divNode" class="panel">Div</div>
You can set multiple values to an attribute by separating the string with space.
divNode.setAttribute("class", "panel panel-group")
This will set the class
attribute with the value panel panel-group
.
<div id="divNode" class="panel panel-group">Div</div>
getAttribute(attrKey)
This method returns the value of an attribute.
Given an element:
<div id="divNode" class="panel panel-group">Div</div>
To get the value of the id
attribute in #divNode
:
divNode.getAttribute("id") // divNode
To get the values of the class
attribute:
divNode.getAttribute("class") // "panel panel-group"
getAttributeNames()
This methods returns in an array all the attibutes in an element.
<div id="divNode" class="panel panel-group">Div</div>
To get all the attributes defined in the div node:
divNode.getAttributeNames() // Array[ "id", "class" ]
cloneNode()
This method clones or replicates a DOM node. It creates another reference of a DOM node so the original is not touched.
This is often used in DOM APIs to remove DOM nodes, such as appendChild
, replaceChild
, etc. These APIs remove the DOM node they are acting on, so if you don’t want the DOM node to be removed, clone the DOM node so the API works on a clone of it without affecting the original copy.
Note: cloneNode
doesn’t clone the element’s child nodes. It just copies the element alone.
For example, let’s say you have a DOM node that you want to append to another DOM node.
<div id="div1Node"> Div 1 </div> <div id="div2Node"> Div 2 </div>
If you want to append #div1Node
to #div2Node
without affecting #div1Node
‘s position (i.e., without removing it from its position), you can clone it using cloneNode
and pass the cloned node to the appendChild
method.
div2Node.appendChild(div1Node.cloneNode())
The outcome:
<div id="div1Node"> Div 1 </div> <div id="div2Node"> Div 2 <div id="div1Node"></div> </div>
#div1Node
is appended to #div2Node
but without its child text node.
To clone a node with its whole children subtree, pass the boolean true
to cloneNode
.
div2Node.appendChild(div1Node.cloneNode(true))
This will copy the #div1Node with its Text child and append them to #div2Node
<div id="div1Node"> Div 1 </div> <div id="div2Node"> Div 2 <div id="div1Node"> Div 1 </div> </div>
classList
This is a property in DOM nodes with an array value. The array contains the values of the class
name in an element.
<div id="divNode" class="panel panel-group item"></div>
The classList
on #divNode
will be:
divNode.classList // DOMTokenList [ "panel", "pane-group", "item" ]
This DOMTokenList
is a subclass of DOMTokenListPrototype
, which contains methods used to manipulate class name values in an element.
add
This adds a new value to an element’s class name.
<div id="divNode" class="panel panel-group item"></div>
To add “item-group” to #divNode class attribute:
divNode.classList.add("item-group")
<div id="divNode" class="panel panel-group item item-group"></div>
contains
Checks whether the class name has a specified value.
<div id="divNode" class="panel panel-group item"></div>
To check if the #divNode’s class attribute has “panel”. We do this:
divNode.classList.contains("panel") // true
item(index)
To retrieve a class value from the list using index style.
For example:
<div id="divNode" class="panel panel-group item"></div>
divNode.classList.item(0) will be panel
divNode.classList.item(1) will be panel-group
divNode.classList.item(2) will be item
remove
This removes a class value from the attribute.
For example:
<div id="divNode" class="panel panel-group item"></div>
To remove a panel from the #divNode
‘s class name:
divNode.classList.remove("panel")
Outcome:
<div id="divNode" class="panel-group item"></div>
replace
This replaces a class value in the list with a new value.
For example:
<div id="divNode" class="panel panel-group item"></div>
To replace “item” in divNode class names with “tab”, we do this:
divNode.classList.replace("item", "tab")
Outcome:
<div id="divNode" class="panel panel-group tab"></div>
toggle
This method removes or adds a specified value to the class names.
If the class name is not in the element, it adds it. If the class name is in the element, it removes it. That’s toggling.
<div id="divNode" class="panel panel-group item"></div>
We can remove/add the “panel” class name, like this:
divNode.classList.toggle("panel")
Outcome:
<div id="divNode" class="panel-group item"></div>
divNode.classList.toggle("panel")
Outcome:
<div id="divNode" class="panel panel-group item"></div>
divNode.classList.toggle("panel")
Outcome:
<div id="divNode" class="panel-group item"></div>
parentNode
This returns the DOM node instance of an element’s parent node.
<div id="divNode"> Parent Node <div id="divChildNode"></div> </div>
To get the parent node of the #divChildNode
:
divChildNode.parentNode // div ParentNode
parentElement
See above; this works the same as parentNode
.
innerHTML
This returns the HTML markup of an element.
For example:
<div id="divNode"> <p>I'm Paragraph</p> <div id="childNode1">Chidl Node 1</div> <div id="childNode2">Child Node 2</div> <div id="childNode3">Child Node 3</div> </div>
The innerHTML
of #divNode
would be:
divNode.innerHTML // "\n <p>I'm Paragraph</p>\n <div id=\"childNode1\">Chidl Node 1</div>\n <div id=\"childNode2\">Child Node 2</div>\n <div id=\"childNode3\">Child Node 3</div>\n"
It is a string representation of the child nodes of the #divNode
element.
innerHTML
is used to build up DOM nodes by concatenating two or more HTML markup strings.
For example:
<div id="divNode"> Div 1 <div>
To add the HTML markup I'm Paragraph
to divNode
:
divNode.innerHTML += "<p>I'm Paragraph</p>"
The DOM outcome will be as follows.
<div id="divNode"> Div 1 <p>I'm Paragraph</p> <div>
To prepend it before the divNode
HTML:
divNode.innerHTL = "<p>I'm Paragraph</p>" + divNode.innerHTML
innerText
This returns the text nodes of an element’s children nodes.
For example:
<div id="divNode"> <p>I'm Paragraph</p> <div id="childNode1">Chidl Node 1</div> <div id="childNode2">Child Node 2</div> <div id="childNode3">Child Node 3</div> </div>
innerText
on divNode
returns in a string all the text nodes contained in the #divNode
. It will run down to its last subtree and collect all the text nodes there.
divNode.innerText // "I'm Paragraph\n\nChidl Node 1\nChild Node 2\nChild Node 3"
If you have any questions regarding the APIs outlined above or suggestions about anything I should add, correct, or remove, feel free to comment, shoot me an email, or DM me.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowBuild scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]