Table of contents
- What is DOM?
- What is window object?
- What is console.dir() ?
- What is console.dir(window) ?
- What is a node and its relationship in the DOM tree?
- Node relationships in the DOM tree:
- Accessing elements of an HTML document:
- Selecting element using DOM
- Difference b/w innerHTML, innerText and textContent.
- Two more selectors are here that we use most nowadays.
What is DOM?
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text content. The DOM provides a way for programs to dynamically manipulate the content, structure, and style of a web document. The DOM is a hierarchical tree-like structure that represents the structure of an HTML or XML document. Each element, attribute, and text content in the document is represented as a node in the tree.
Here is 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>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<img src="example.img" alt="image Here" class="img">
<h1></h1>
<div>
<p>This is a paragraph</p>
</div>
</div>
<script></script>
</body>
</html>
You can understand the DOM tree of the above HTML document from the picture given below.
What is window
object?
Thewindow
object is a fundamental part of the JavaScript programming language, and it represents the global environment in a web browser. It is a top-level object that serves as the global context for all JavaScript code running within a browser environment. The window
object is the global object in a browser environment. Any variable or function declared globally becomes a property or method of the window
object. Thewindow
object has various properties, some of which are predefined and others that are added by the browser. Common properties include document
(represents the HTML document), location
(provides information about the URL), navigator
(information about the browser), and console
(for logging and debugging).
For Example:
console.log(window.location.href); // Run in the console of the browser.
// Outputs the current URL
Thewindow
object also includes several methods. One commonly used method is alert()
, which displays a dialog box with a specified message.
For Example:
window.alert("This is JavaScript Blog!");
As it represents the global environment in a web browser if you don't use awindow
keyword, the browser automatically understands it.
For Example:
alert("This is JavaScript Blog!");
Thewindow
object can be used to interact with frames and popup windows. For example, you can reference other frames or open new browser windows.
For Example:
window.open("https://www.example.com", "_blank");
Thewindow
object is involved in handling various events that occur in the browser, such as the load
event.
For Example:
window.onload = function() {
console.log("Page is loaded");
};
Thewindow
object provides two storage mechanisms for storing key/value pairs: localStorage
andsessionStorage
. These can be used to persist data between page reloads or sessions.
For Example:
window.localStorage.setItem("username", "Muhammad Bilal");
Thewindow
object plays a role in enforcing security policies in the browser. It is involved in handling cross-origin communication restrictions and provides mechanisms such as the Same-Origin Policy.
What is console.dir()
?
In JavaScript, console.dir()
a method is provided by theconsole
object that is used for debugging and logging. It is often employed to display an interactive listing of the properties of a specified JavaScript object. Theconsole.dir()
method takes an object as an argument and outputs an interactive list of the object's properties to the console. This can be especially useful when dealing with complex objects or when you want to explore the structure of an object in more detail.
For Example:
let user = {
firstName: "Muhammad",
lastName: "Bilal",
age: 21,
}
console.dir(user);
``````````````````````````````````````````````````````````
// Run it in the console like in the image below.
What is console.dir(window)
?
To print a detailed listing of the properties of the window.
console.dir(window) // Run it in cosole like the image given below
In JavaScript, console.dir(window)
is a command used to print a detailed listing of the properties of the window
object to the console. Theconsole.dir()
method is commonly used for inspecting complex objects in a more readable way thanconsole.log()
.
What is a node and its relationship in the DOM tree?
In the context of web development, a "node" refers to a fundamental building block in the Document Object Model (DOM). The DOM represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text. The DOM tree is a hierarchical structure with a root node that represents the entire document. Each element, attribute, and piece of text in the document is represented by a node in the tree. Nodes have various types, such as element nodes, attribute nodes, and text nodes.
Node relationships in the DOM tree:
The relationships between nodes in the DOM tree can be categorized into parent-child relationships and sibling relationships.
Parent-Child Relationship:
Each node in the DOM tree, except for the root, has a parent node. The node that is contained within another node is considered its child.
For example, in the HTML structure, the <div>
element node is the parentNode of the <p>
element and <p>
element is the childNode of the element <div>
. <p>
is the previousSibling of <li>
and<li>
is the nextSibling of <p>
.
<div>
<p>Lorem ipsum dolor sit amet.</p>
<li>Lorem ipsum dolor sit amet.</li>
</div>
Accessing elements of an HTML document:
For example, this is an HTML document:
Let's access the elements of this document one by one:
If you want to print the <head>
section in the console, then write
console.log(document.head);
If you want to access <div>
element in the given document, then write
console.log(document.body.childNodes[1])
If you want to change the text content of <p>
tag, then write
// This access the the p tag
let changeText = document.body.childNodes[1].childNodes[1];
console.log(changeText)
Output: <p> Lorem ipsum dolor, sit. </p>
// Now change the text in p and check it again
changeText.innerText = "Text is changed";
console.log(changeText);
Output: <p> Text is changed </p>
Let's see manipulation in HTML documents using some DOM methods.
Selecting element using DOM
In JavaScript, you can use the Document Object Model (DOM) to interact with HTML and XML documents. The DOM provides a structured representation of the document, and you can use JavaScript to manipulate the content, structure, and style of the document.
There are the following methods; let's discuss them one by one.
getElementById()
ThegetElementById()
method is a fundamental and widely used method in JavaScript that allows you to retrieve a reference to an HTML element on a web page based on its unique ID. This method is part of the Document Object Model (DOM) API, which represents the structure of an HTML document as a tree of objects. This is a quick way to access the element.
For Example:
<!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>
<p id="message">
JavaScript DOM Started.
</p>
</div>
</body>
</html>
If you have this structure, then in a script tag (<script>
) or in a JavaScript file that is linked to the HTML, you can access it directly from the HTML document
let msg = document.getElementById("message");
console.log(msg);
Output: <p id="message"> JavaScript DOM Started. </p>
Note:
If there is no<id>
attribute in the document, then it returns,null
and if there is more than one <id>
attribute with a message, then it returns the first one only.
For Example in the example below it returns the first one only:
<body>
<div>
<p id="message"> JavaScript DOM Started. </p> // First one
<p id="message"> JavaScript DOM Started. </p>
<p id="message"> JavaScript DOM Started. </p>
</div>
</body>
getElementsByName()
The getElementsByName()
method is used to retrieve a collection of HTML elements with a given name
attribute. This method is often used with form elements like input fields, radio buttons, and checkboxes.
For Example:
<!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>
<input type="radio" name="language" value="JavaScript">
<input type="radio" name="language" value="Cpp">
<input type="radio" name="language" value="Python">
</div>
</body>
</html>
If you have this structure, then in a script tag (<script>
) or in a JavaScript file that is linked to the HTML, you can access it directly from the HTML document
let inputValues = document.getElementsByName("language");
console.log(inputValues);
Output:
getElementsByTagName()
The getElementsByTagName()
method is a part of the Document Object Model (DOM) in JavaScript, and it is used to retrieve a collection of elements with a specified tag name from the document. This method is particularly useful when you want to select multiple elements of the same type.
For Example:
<!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>
<h1 id="h1">This is Heading 1</h1>
<h1>This is Heading 2</h1>
<h1>This is Heading 3</h1>
<h1>This is Heading 4</h1>
</div>
</body>
</html>
If you have this structure, then in a script tag (<script>
) or in a JavaScript file that is linked to the HTML, you can access it directly from the HTML document
let allHeadings = document.getElementsByTagName("h1");
console.log(allHeadings);
Output: Returns the HTML collection with a length of 4.
If you want to change its inner text then change it using indexing ([0]
) because there can be more than one tag but if you want to change all tags at the same time then you have to run a loop. Let's see an example using the index.
let allHeadings = document.getElementsByTagName("h1")[0];
allHeadings.innerText = "Heading Changed";
Output: the text of the first h1 tag is changed to Heading Changed.
getElementsByClassName()
In JavaScript, the getElementsByClassName()
method is used to retrieve a collection of elements on a web page that have a specific class name. This method is particularly useful when you want to select multiple elements of the same class.
For Example:
<!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>
<h1 class="print">This is Heading 1</h1>
<p class="print">This is para 1</p>
<h3 class="print">This is mini heading</h3>
</div>
</body>
</html>
If you have this structure, then in a script tag (<script>
) or in a JavaScript file that is linked to the HTML, you can access it directly from the HTML document
let classes = document.getElementsByClassName("print");
console.log(classes);
Output: Returns the HTML collection with a length of 3.
If you want to change its inner text then change it using indexing ([0]
) because there can be more than one tag but if you want to change all tags at the same time then you have to run a loop. Let's see an example using the loop.
let classes = document.getElementsByClassName("print");
for (let i = 0; i < classes.length; i++) {
let changedClasses = classes[i].innerHTML = "Heading Changed";
console.log(changedClasses);
}
Output: the text of all three headings is changed to Heading Changed.
Difference b/w innerHTML
, innerText
and textContent
.
innerHTML
innerHTML
deals with the raw HTML content of an element. It returns all the tags and style content present within the selected tag.
For example:
<!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>
<ul>
<li id="nodeElem">
Home <span style="display: none;"> Another hidden Li </span>
</li>
</ul>
</div>
</body>
</html>
If you have this structure, then in a script tag (<script>
) or in a JavaScript file that is linked to the HTML,
let innerHtml = document.getElementById("nodeElem").innerHTML;
console.log(innerHtml);
Output: Home <span style="display: none;"> Another hidden Li </span>
innerText
innerText
deals with the visible text content, excluding HTML tags.
For example:
<!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>
<ul>
<li id="nodeElem">
Home <span style="display: none;"> Another hidden Li </span>
</li>
</ul>
</div>
</body>
</html>
If you have this structure, then in a script tag (<script>
) or in a JavaScript file that is linked to the HTML,
let innerText = document.getElementById("nodeElem").innerText;
console.log(innerText);
Output: Home
textContent
textContent
deals with all text content, including that within HTML tags, whether visible or not.
For example:
<!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>
<ul>
<li id="nodeElem">
Home <span style="display: none;"> Another hidden Li </span>
</li>
</ul>
</div>
</body>
</html>
If you have this structure, then in a script tag (<script>
) or in a JavaScript file that is linked to the HTML,
let textContent = document.getElementById("nodeElem").textContent;
console.log(textContent);
Output: Home Another hidden Li
Two more selectors are here that we use most nowadays.
querySelector()
The querySelector()
method in JavaScript is a DOM (Document Object Model) method that allows you to select the first element that matches a specified CSS selector. It is part of the DOM API and is commonly used to find and interact with HTML elements on a web page.
For example here is the 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>
<h1 class="print">This is Heading 1</h1>
<p id="para">This is para 1</p>
<h3 class="print">This is mini heading</h3>
</div>
</body>
</html>
If you want to select h1
tag by using class then, in a script tag (<script>
) or in a JavaScript file that is linked to the HTML, you can access it directly from the HTML document
let classSelector = document.querySelector(".print").innerHTML;
console.log(classSelector);
Output: This is Heading 1
If you want to select p
tag by using ID then
let idSelector = document.querySelector("#para").innerHTML;
console.log(idSelector);
Output: This is para 1
If you want to select h3
tag by using the tag name directly then
let selectByTag = document.querySelector("h3").innerHTML;
console.log(selectByTag);
Output: This is mini heading
querySelectorAll()
The querySelectorAll()
method is a DOM (Document Object Model) method in JavaScript that is used to select and return a NodeList of elements that match a specified CSS selector. It is part of the DOM Level 4 specification and is widely supported in modern browsers. It's important to note that a NodeList is not an array, but you can iterate over it using methods like forEach()
. Keep in mind it returns the NodeList of elements, not an array.
For example here is the 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>
<ul>
<li class="nodeElem">Home</li>
<li class="nodeElem">About</li>
<li class="nodeElem">Contact</li>
<li class="nodeElem">FAQs</li>
</ul>
</div>
</body>
</html>
If you want to print li
by using querySelector()
then it prints only the first li
. It also does not allow iteration. You can do this by using querySelectorAll()
to print every li
by using iteration. Let's see an example:
let everyLi = document.querySelectorAll("li");
for (let i = 0; i < everyLi.length; i++) {
let changedClasses = everyLi[i].innerHTML;
console.log(changedClasses);
}
Output:
Home
About
Contact
FAQs
You can also do it using foreach
loop. and this time we will check it in the given class.
let everyLi = document.querySelectorAll(".nodeElem");
everyLi.forEach(element => {
console.log(element.innerHTML);
});
Output:
Home
About
Contact
FAQs