Diving into Document Object Model (DOM) Manipulation with JavaScript
The Document Object Model (DOM) is a crucial aspect of web development, allowing developers to interact with and manipulate the structure, style, and content of HTML documents dynamically. In this article, we will delve into the core concepts of the DOM, exploring its structure, functionality, and how it facilitates the creation of interactive web pages.
What is DOM in JavaScript?
The Document Object Model (DOM) is a programming interface for HTML It represents the hierarchical structure of HTML or XML documents as a tree of objects, where each object corresponds to elements, attributes, and text within the HTML.
The DOM provides a standardized way for programs, typically written in languages like JavaScript, to dynamically access, manipulate, and modify the content, structure, and style of HTML. It acts as an interface that allows developers to interact with and modify the elements of an HTML page through scripting.
Why did we use DOM?
The Document Object Model (DOM) is used for several important purposes in web development:
Dynamic Content Manipulation: The DOM allows developers to dynamically manipulate the content, structure, and style of web documents using scripting languages like JavaScript. This enables the creation of interactive and dynamic web pages.
User Interface (UD Interactivity): Developers can use the DOM to respond to user actions such as clicks, inputs, and other events. This interaction is crucial for creating responsive and user-friendly web applications.
Dynamic Styling: Developers can use the DOM to dynamically apply or change styles on HTML elements based on certain conditions or user interactions, allowing for dynamic and responsive designs.
The DOM is essential for dynamic web development because it enables the modification of document content, structure, and style in real-time. By using the DOM, developers can create interactive and responsive web pages, making it a fundamental tool in modern web development.
DOM Tree A Hierarchical Representation and Main Node Types
The DOM tree, or Document Object Model tree, is a hierarchical representation of the structure of an HTML or XML document. It is created by web browsers when they parse the markup language of a webpage. The tree structure consists of nodes, each representing a part of the document, such as elements, attributes, or text content.
Here’s a brief overview of the key components of the DOM tree:
What is DOM Traversing?
DOM traversing refers to the process of navigating through the Document Object Model (DOM) tree to access and manipulate elements based on their relationships with other elements. The DOM represents the hierarchical structure of HTML or XML documents, where each HTML element is a node in the tree. Commonly used methods for DOM traversing include.
Root node: The root node is the highest in the DOM tree hierarchy, representing the entire HTML or XML document.
Parent Node: The parent node is a node that has one or more child nodes directly below it in the hierarchy.
Child node: A child node is a node that is directly below another node (its parent) in the hierarchy.
First Child: A node's first child is the node directly below it and is the first among its immediate children.
Last Child: The last child of a node is the node that is directly below it and is the last among its immediate children.
Document Node: At the top of the tree is the document node, representing the entire HTML or XML document. It serves as the root of the DOM tree.
Element nod: Element nodes in the HTML or XML document, such as , “<div”, or “<p>”,<a>, become element nodes in the DOM tree. Element nodes can have children (other nodes) and attributes.
Attribute Nodes: Attributes of HTML or XML elements become attribute nodes in the DOM tree. These nodes provide information about the corresponding element.
Text node: The textual content within HTML or XML elements becomes text nodes in the DOM tree. For example, the text between,”<p>” and “</p>”, tags becomes a text node.
Comment Nodes: Comments in the document are also represented as nodes in the DOM tree.
What is DOM Manipulation?
DOM manipulation refers to the process of dynamically modifying the structure, content, or style of a web page using JavaScript. The DOM (Document Object Model) represents the structure of an HTML or XML document as a tree of objects, and JavaScript provides methods and properties to interact with and modify this tree.
DOM manipulation allows developers to create dynamic and responsive web pages by changing elements, updating content, and responding to user actions.
Attribute: an attribute typically refers to a property or characteristic of an HTML element, and it can be accessed and manipulated using the DOM (Document Object Model). HTML elements can have various attributes, such as id, class, src,href, style, etc. These attributes provide additional information about the elements and influence their behavior, appearance, or functionality.
Here are some common tasks associated with DOM manipulation:
Accessing HTML tags by ID names
IDs must be unique within an HTML document. You cannot have multiple elements with the same ID.
<p id="toget"> this is a paragraph tag which has a id attribute </p>
let attr = document.getElementById("toget")
console.log(attr)
Accessing HTML tags by class names
Classes, on the other hand, can be shared among multiple elements. Multiple elements can have the same class. you can select one OR multiple elements of the same class name at a time using various JavaScript methods.
<p class="Myclass"> this is a paragraph tag which has a id attribute </p>
let attr = document.getElementsByclassName("Myclass")
console.log(attr)
Accessing HTML tags by tag names
you can select one OR multiple elements of the same tag at a time using various JavaScript methods.
<p> this is a paragraph tag which has a id attribute </p>
let attr = document.getElementsBytagName("p")
console.log(attr)
“ querySe1ector ” is a method in JavaScript that allows you to select and retrieve the first element in the document that matches a specified CSS selector. It is part of the Document Object Model (DOM) API and provides a powerful way to locate elements using CSS-style selectors.
Examples
Selecting by Tag Name:
<p> this is a paragraph tag which has we can get this by using queryselector </p>
let fortag = document.querySelector("p")
//onsole.log(fortag)
fortag.style.backgroundColor="red"
Selecting by class Names :
<p class= "Myclass"> this is a paragraph which has class we can get this by using queryselector </p>
let forclass = document.querySelector(" .Myclass")
//console.log(forclass)
forclass.style.backgroundColor="green"
Selecting by class ID Names :
<p id =" thisid " > this is a paragraph with id which has we can get this by using queryselector </p>
let forid = document.querySelector(" # thisid")
//console.log(forid)
forid.style.backgroundColor="blue"
“ querySe1ectorA11" is a method in JavaScript that allows you to select multiple elements in the DOM using a CSS selector and returns a static Node List representing the list of elements that match the specified selector.
Examples
Selecting by Tag Name:
let paragraphs = document.querySelectorAll("p");
console.log(paragraphs)
//in the console all the p tag are return
Selecting by class Name:
let ElementsWithClass = document.querySelectorAll(".ExampleClass");
console.log(ElementsWithClass)
//in the console all the tags are return which has class name ElementsWithClass
Selecting by ID:
let ElementsWithID = document.querySelectorAll("#ExampleID");
console.log(ElementsWithID)
//in the console only one tag return which has id name ElementsWithID
While you can use “ querySe1ectorA11” with an ID selector, it’s less common, as IDs should be unique. If you want just one element, it’s more typical to use getEIementBy1d.
DOM Essentials Tags, Inner Text, Append, Before, Remove, get, set
To get the Attribute class Name
<div class="theDivClass">this is a div having the id name theDiv </div>
let togetClass = document.querySelector("div")
let Myclass = togetClass.getAttribute("class")
console.log(Myclass) //theDivClass
To get attribute ID Name
<div id="theDiv">this is a div having the id name theDiv </div>
let toget = document.querySelector("div")
let id = toget.getAttribute("id")
console.log(id) //theDiv
To set a new class Attribute Name
<div class="newone">this is a div having the id name theDiv </div>
let togetClass = document.querySelector("div")
let Myclass = togetClass.setAttribute("newone" , " mynewclass ")
console.log(Myclass)
To set a new ID attribute Name
<p id="myid"> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Error, ipsam?</p>
let togetClass = document.querySelector("p")
let Myclass = togetClass.setAttribute("myid" , " mynewid ")
console.log(Myclass)
Inner text
<p>the inner text key word is used to console the taxt inside any tag </p>
let para= document.querySelector("p")
console.log(para.innerText)
Creating, Setting Content, and Appending Elements
<div class="main">
<ul>
<li>home</li>
<li>contact</li>
<li>About us</li>
</ul>
</div>
let Newbtn=document.createElement("button")
/* Here, a new element is created in the DOM using the
document.createE1ement() method. The new button is stored in the variable
Newbtn */
Newbtn.innerText="click me !"
console.log(Newbtn)
/*The innerText() property is used to set the text content of the newly created button.
In this case, the text is set to "click me !". */
let toadd=document.querySelector("div")
toadd.append(Newbtn)
/*The append method adds the specified element as the last child
of the parent element. In this case, the newly created "button" is added as the
last child of the selected element. */
Prepend a button
<div class="main">
<ul>
<li>home</li>
<li>contact</li>
<li>About us</li>
</ul>
</div>
/*The 'prepend' method adds a specified element as the first child of another element,
allowing dynamic content insertion at the beginning of the DOM structure.*/
let Newbtn=document.createElement("button")
Newbtn.innerText="click me !"
console.log(Newbtn)
let toadd=document.querySelector("div")
toadd.prepend(Newbtn)
Add a button before the “div” tag
<div class="main">
<ul>
<li>home</li>
<li>contact</li>
<li>About us</li>
</ul>
</div>
/*
The 'before' method in JavaScript inserts a specified element before a target element,
altering the DOM structure by placing content before the target.*/
let Newbtn=document.createElement("button")
Newbtn.innerText="click me !"
console.log(Newbtn)
let toadd=document.querySelector("div")
toadd.before(Newbtn)
Add a button after the “div” tag
<div class="main">
<ul>
<li>home</li>
<li>contact</li>
<li>About us</li>
</ul>
</div>
/*"The 'after' method in JavaScript inserts a specified element after a target element,
modifying the DOM structure to position content after the target element." */
let Newbtn=document.createElement("button")
Newbtn.innerText="click me !"
console.log(Newbtn)
let toadd=document.querySelector("div")
toadd.after(Newbtn)
To delete a tag using the remove method
<p>to delete any tag we can used remove key word </p>
/*The 'remove' method in JavaScript deletes a specified element from the DOM,
effectively removing it and its content from the document structure */
let para= document.querySelector("p")
para.remove();
What is an Event?
Events are things that happen in the system you are programming — the system produces (or “fires”) a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs. Events are fired inside the browser window and tend to be attached to a specific item that resides in it. This might be a single element, a set of elements, the HTML document loaded in the current tab, or the entire browser window. Many different types of events can occur.
For example:
• The user selects, clicks, or hovers the cursor over a certain element.
• The user chooses a key on the keyboard.
• The user resizes or closes the browser window.
• A web page finishes loading.
• A form is submitted.
• A video is played, paused, or ends.
• An error occurs.
What is an event handler?
To react to an event, you attach an event handler to it. This is a block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are registering an event handler.
Note: Event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code run in response to it happening.
Web events are not part of the core JavaScript language — they are defined as part of the APIs built into the browser.
examples
Multi-Event Click Analysis: Capturing and Logging Click Events on Button
<button id="btn1">click me once!</button>
let click=document.querySelector(" #btn1")
/* The addEventListener method typically associates a single event type with a specific
HTML element. If you want to handle multiple events for the same element,
you would generally use multiple calls to , each specifying a different event
type. */
click.addEventListener("click", ()=>{
console.log("button 1 was click")
})
click.addEventListener("click", ()=>{
console.log("button 2 was click")
})
click.addEventListener("click", ()=>{
console.log("button 3 was click")
})
click.addEventListener("click", ()=>{
console.log("button 4 was click")})
Toggle Mode Switch: Dynamically Changing Page Theme on Button Click
<button id="mode"> change mode</button>
let modeBtn = document.querySelector("#mode");
console.log(modeBtn);
let currMode = "light";
modeBtn.addEventListener("click", () => {
if (currMode === "light") {
currMode = "dark";
document.body.style.backgroundColor = "black";
} else {
currMode = "light";
document.body.style.backgroundColor = "white";
}
console.log(currMode);
});
Interactive Button Click Logging Event and Incrementing Counter
<button id="btn"> click Me !</button>
let btn2 = document.querySelector("#btn")
btn2.onclick =()=>{
console.log("button one was click")
let a=23;
a++;
console.log(a)
}
Dynamic Hover Effect Changing Text Color on Mouse Over
<div>this is a box</div>
let box = document.querySelector("div")
box.onmouseover = () =>{
console.log("you pointer is on the box")
box.style.color="red"
}
Changing Text Color and Background on Mouse Out Event
<div>this is a box</div>
let box = document.querySelector("div")
box.onmouseout = () =>{
console.log("you pointer is on the box")
box.style.color="red"
box.style.backgroundColor="blue"
}
Conclusion
The Document Object Model (DOM) plays a pivotal role in web development, enabling dynamic interaction and manipulation of HTML documents. DOM manipulation, achieved through JavaScript, empowers developers to create responsive and interactive web pages by dynamically modifying content, structure, and styles. Understanding the DOM tree structure, traversal methods, and essential concepts like events and event handlers is fundamental to effective web development.
The ability to dynamically create, set content, and append elements, along with practical examples of DOM manipulation, showcases the versatility and power of JavaScript in enhancing the user experience.