DOM Manipulation (Part-3) Manipulation of HTML elements and style elements in JavaScript in depth
Manipulation of HTML elements
Creating HTML elements
Creating HTML elements using the DOM is a common task in web development. The DOM allows you to interact with and manipulate the structure and content of an HTML document dynamically. Let's create it, then add an ID or class to that element, then add text or values to the element, and then show it on our webpage step by step.
For example, if you want to create a div tag, then
let divElem = document.createElement('div');
console.log(divElem);
Output: <div></div> // Output will show in console
Now set an ID and a class in a div element
divElem.className = 'main';
divElem.id = 'myId';
console.log(divElem);
Output: <div class="main" id="myId"></div> // Output will show in console
ID and class are the default attributes. What if you need to add a custom attribute to our newly created element?<div>
For that, we use setAttribute
setAttribute()
ThesetAttribute
method is part of the DOM API in web development. It is used to set the value of an attribute on a specified element. It takes two attributes. The first is attributeName
and the second is attributeValue
For example:
We add custom attributes in our previously created element.<div>
divElem.setAttribute('title', 'myTitleElement');
console.log(divElem);
// Output will show in console
Output: <div class="main" id="myId" title="myTitleElement"></div>
Now add text to the created element;div
we can add the text by using innerText
, textContent
, or,innerHTML
but the best method we have for this iscreateTextNode
.
// Using innerHTML
divElem.innerHTML = 'This is the innerHTML.';
console.log(divElem);
Output: <div class="main" id="myId" title="myTitleElement">This is the innerHTML.</div>
// Using innerText
divElem.innerText = 'This is the innerText.';
console.log(divElem);
Output: <div class="main" id="myId" title="myTitleElement">This is the innerText.</div>
// Using textContent
divElem.textContent = 'This is the textContent.';
console.log(divElem);
Output: <div class="main" id="myId" title="myTitleElement">This is the textContent.</div>
Now add text to the created element;div
for that, we havecreateTextNode
.
createTextNode()
In the DOM, thecreateTextNode
method is used to create a new text node. Text nodes represent the textual content of an element in an HTML or XML document. ThecreateTextNode
method is often used in conjunction with other DOM methods to manipulate or update the content of an HTML element.
For Example:
let textNode = document.createTextNode('This is div element');
divElem.appendChild(textNode)
console.log(divElem);
// Output will show in console
Output: <div class="main" id="myId" title="myTitleElement">This is div element</div>
Now we have to include thisdiv
in our HTML document.
// Output will show in Your document file
document.body.appendChild(divElem);
Output: This is div element
appendChild()
In the DOM, the appendChild
method is used to add a node to the end of the list of the children of a specified parent node. The node to be added is passed as an argument to the appendChild
method.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Blog</li>
</ul>
</body>
</html>
If you want to add one more li
with the name of Contact
dynamically, then write in script
let menu = document.getElementById("menu");
let list = document.createElement("li");
list.innerHTML = "Contact";
menu.appendChild(list)
Output:
Home
About
Blog
Contact
append()
append()
method in JavaScript that allows you to append one or multiple nodes or strings to the end of a parent node. It's convenient for appending multiple items in a single call.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Blog</li>
</ul>
</body>
</html>
If you want to add one more li
with the name of Contact
and an div
element and p
elements with text dynamically, then write in script
let menu = document.getElementById("menu");
// Creating li element
let list = document.createElement("li");
list.innerHTML = "Contact";
// Creating div element
let list1 = document.createElement("div");
list1.innerHTML = "This is the div";
// Creating p element
let list2 = document.createElement("p");
list2.innerHTML = "This is the Paragraph";
// appending all of these into the selected id menu
menu.append(list, list1, list2);
Output:
Home
About
Blog
Contact
This is the div
This is the Paragraph
Difference between append
andappendChild
?
The key difference lies in the flexibility and convenience of the append()
method. With append()
, you can append multiple nodes or strings in a single call, making the code cleaner and more concise. On the other hand, appendChild()
is more traditional and requires multiple calls if you want to append multiple nodes. It's worth noting that append()
is more versatile and allows you to append various types of content whileappendChild()
specifically dealing with nodes. Both methods achieve the same goal of adding elements to the DOM but append()
are often preferred for their simplicity.
prepend()
In JavaScript, when we talk about "prepend" in the DOM, we mean adding elements or content at the beginning of a parent node. It adds an element before the specified or targeted element.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Blog</li>
</ul>
</body>
</html>
If you want to add one more li
with the name of Contact
and an div
element and p
elements with text dynamically, then write in script
let menu = document.getElementById("menu");
// Creating div element
let list = document.createElement("div");
list.innerHTML = "This is the div";
menu.prepend(list)
Output:
This is the div
Home
About
Blog
after()
In JavaScript, when we talk about "after" in the DOM, we mean adding elements or content after the specified element. It adds an element after the specified or targeted element.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li id="second-li">About</li>
<li>Blog</li>
</ul>
</body>
</html>
If you want to add one more div
element with text after the second li
dynamically, then write in script
// selecting id menu
let menu = document.getElementById("menu");
// selecting id second-li
let listed = document.getElementById("second-li");
// Creating div element dynamically
let list = document.createElement("div");
// Inserting textNode into the div
list.innerHTML = "This is the div element.";
// appending created div element in to the selected id menu
menu.appendChild(list);
// setting the position of the appended div
listed.after(list)
Output:
Home
About
This is the div element.
Blog
before()
In JavaScript, when we talk about "before" in the DOM, we mean adding elements or content before the specified element. It adds an element before the specified or targeted element.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li id="second-li">About</li>
<li>Blog</li>
</ul>
</body>
</html>
If you want to add one more div
element with text before the second li
dynamically, then write in script
// selecting id menu
let menu = document.getElementById("menu");
// selecting id second-li
let listed = document.getElementById("second-li");
// Creating div element dynamically
let list = document.createElement("div");
// Inserting textNode into the div
list.innerHTML = "This is the div element.";
// appending created div element in to the selected id menu
menu.appendChild(list);
// setting the position of the appended div
listed.before(list)
Output:
Home
This is the div element.
About
Blog
insertAdjacentHTML()
TheinsertAdjacentHTML()
is a DOM method that allows you to insert HTML elements or text into a specified position relative to the current element in the DOM structure. It provides a way to dynamically add HTML content to a document. It takes two arguments: the first is the position name, and the second is the text. Both arguments are in the form of a string.
The position name has four further positions:
beforebegin
afterbegin
beforeend
afterend
Let's see an example with all of these If you have an HTML document,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li id="second-li">About</li>
<li>Blog</li>
</ul>
</body>
</html>
If you want to add one more div
element with text before and after the second li
dynamically, then write in script
beforebegin
let menu = document.getElementById("menu"); menu.insertAdjacentHTML("beforebegin", "<li>Contact</li>"); Output: It will show Contact before the ul starting tag // like Contact // ul tag starts from here Home About Blog
afterbegin
let menu = document.getElementById("menu"); menu.insertAdjacentHTML("afterbegin", "<li>Contact</li>"); Output: It will show Contact after the ul starting tag and before Home // like Contact Home About Blog
beforeend
let menu = document.getElementById("menu"); menu.insertAdjacentHTML("beforeend", "<li>Contact</li>"); Output: It will show Contact after the Blog and before ending ul tag // like Home About Blog Contact
afterend
let menu = document.getElementById("menu"); menu.insertAdjacentHTML("afterend", "<li>Contact</li>"); Output: It will show Contact after the ending ul tag // like Home About Blog // ul tag ends here Contact
replaceChild()
In the DOM, the replaceChild
method is used to replace a child node with another node within a parent node. It is a method of the Node
interface in the DOM. It takes two arguments: the first is a new node, and the second is an old node.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<div id="main">
<p id="para1">This is paragraph one.</p>
<p id="para2">This is paragraph two.</p>
</div>
</body>
</html>
If you want to replace the second para
dynamically, then write in script
let parentNode = document.getElementById('main');
let oldElem = document.getElementById('para2');
// creating new paragraph
let newElem = document.createElement('p');
newElem.innerText = 'This is the new paragraph.';
// replacing new with old one
parentNode.replaceChild(newElem, oldElem);
Output:
This is paragraph one.
This is the new paragraph.
cloneNode()
In the DOM, the cloneNode()
method is used to create a duplicate of a node. The cloneNode()
method is available on all DOM nodes, and it allows you to create a copy of a node, optionally including its descendants.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<div id="main">
<p id="para1">This is paragraph one.</p>
<p id="para2">This is paragraph two.</p>
</div>
</body>
</html>
If you want to clone the main element node, then write in script
let parentNode = document.getElementById('main');
// clone the div element
let cloneNode = parentNode.cloneNode();
console.log(cloneNode);
Output: <div id="main"></div>
cloneNode()
takes a parameter true
If you provide this parameter, then it clones the node deeply with all of its children. By default, it isfalse
. For example:
let parentNode = document.getElementById('main');
// clone the div element
let cloneNode = parentNode.cloneNode(true);
console.log(cloneNode);
Output:
<div id="main">
<p id="para1">This is paragraph one.</p>
<p id="para2">This is paragraph two.</p>
</div>
removeChild()
In the DOM, aremoveChild()
method is used to remove a specified child node from the parent node. This method is typically called on a parent element, and it requires a reference to the child node that you want to remove.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<div id="main">
<p id="para1">This is paragraph one.</p>
<p id="para2">This is paragraph two.</p>
</div>
</body>
</html>
If you want to remove the second p
element node, then write in script
let parentNode = document.getElementById('main');
parentNode.removeChild(parentNode.lastElementChild);
Output: This is paragraph one. // There left only this on the web page
insertBefore()
In the DOM, ainsertBefore()
method is used to insert a new node before an existing child node within a parent node. This method is commonly used to dynamically manipulate the structure of a web page by adding or reordering elements.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
If you want to insert the new element node p
before item 2
, then write in script
// Get the parent node
let myList = document.getElementById('myList');
// Create a new p element
let newItem = document.createElement('p');
newItem.textContent = 'New Item';
// Get the reference node (the second list item (Item 2) in this case)
let referenceNode = myList.children[1];
// Insert the new item before the reference node
myList.insertBefore(newItem, referenceNode);
Output:
Item 1
New Item
Item 2
Item 3
Now let's talk about manipulating element's styles
For manipulating element's styles in the DOM, we use the style property.
style property
In the DOM, the style property is used to access and manipulate the inline style of an HTML element. Each HTML element can have an associated set of styles defined either in a separate stylesheet or inline using the "style" attribute. The style property in the DOM allows you to work with these inline styles programmatically.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
// This ul will show in red color
<ul id="myList" style="color: red; list-style: none;">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
If you want to change the color or background color of li
tags, then write in script
// Get the id myList of ul node
let myList = document.getElementById('myList');
// Changing css using style
myList.style.color = "green";
myList.style.backgroundColor = "yellow"
// Now the color of li tags is green and background color is yellow.
cssText property
ThecssText
property in the DOM is used with CSSStyleDeclaration
objects to get or set the entire textual representation of the style declaration. It represents the entire style declaration as a string, including all properties and values. If there is another property before, then it will overwrite that.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
// This ul will show in red color
<ul id="myList" style="color: red; list-style: none;">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
If you want to change the background color of li
tags and also add some padding, then write in script
// Get the id myList of ul node
let myList = document.getElementById('myList');
// Changing css using style
myList.style.cssText = "background-color:yellow";
Now the background color is yellow. But other CSS styles were removed because this would overwrite them. If you want both properties, then you will have to concatenate them.
For example:
// Changing css using style
myList.style.cssText += "background-color:yellow";
Now the background color is yellow. Other CSS styles are also present.
Using this, cssText
you can add multiple properties at the same time using a semicolon;
.
For Example:
// Changing css using style
myList.style.cssText += "background-color:yellow; padding:20px; color: blue";
Keep in mind that modifyingcssText
directly may override existing styles, so use it carefully.
getComputedStyle()
The getComputedStyle()
method of the DOM is used to retrieve the computed style of an element. It returns an object that represents the final, computed values of all the CSS properties of the specified element after applying all stylesheets and resolving any inherited styles. This is the window
object.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
<style>
ul{
color: red;
list-style: none;
}
</style>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
If you want to get element-style properties, then write in script
// Get the id myList of ul node
let myList = document.getElementById('myList');
console.log(window.getComputedStyle(myList));
// This show all the css applied at that
// To get the particular value then
console.log(window.getComputedStyle(myList).color);
Output: red (in rgb)
classList property
In the DOM, theclassList
property is used to manipulate the class attributes of an HTML element. It provides an easy way to add, remove, toggle, and check for the existence of classes on an element.
For example, If you have an HTML document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Understanding DOM</title>
</head>
<body>
<div id="myPara" class="main">
<p class="para1">This is paragraph one.</p>
<p>This is paragraph two.</p>
</div>
</body>
</html>
add
If you want to add one or more classesmyPara
, then write in script
let myPara = document.getElementById('myPara');
myPara.classList.add("myClass");
console.log(myPara); // in console you will see div has also a class myClass
remove
If you want to remove one or more classesmyPara
, then write in script
let myPara = document.getElementById('myPara');
myPara.classList.remove("main");
console.log(myPara); // in console you will see div has no class
contains
If you want to check if contains one or more classesmyPara
, then write in script
let myPara = document.getElementById('myPara');
let check = myPara.classList.contains("main");
console.log(check); // in console you will see true
replace
If you want to replace one class with anothermyPara
, then write in script
let myPara = document.getElementById('myPara');
myPara.classList.replace("main", "newClass");
console.log(myPara);// in console you will see replaces class as a newClass
toggle
If you want to toggle one classesmyPara
, then write in script
If a class is present thentoggle
remove it and if it is not present thentoggle
adds that class. For example:
let myPara = document.getElementById('myPara');
myPara.classList.toggle("newClass");
console.log(myPara); // This will add class having name newClass
let myPara = document.getElementById('myPara');
myPara.classList.toggle("main");
console.log(myPara); // This will remove class because it already present