0% found this document useful (0 votes)
23 views24 pages

Kaagaz 20241123 203228846917

NA THIS IS THE TUTLE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views24 pages

Kaagaz 20241123 203228846917

NA THIS IS THE TUTLE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

What is the DOM?

Definition: The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of a document in a tree-like format, allowing programs to interact with
the document's content, structure, and style dynamically.
Language: The DOM can be accessed and manipulated using JavaScript.

Structure of the DOM


The DOM represents a document as a hierarchy of nodes, where each node corresponds to a part
of the document.
Node Types:

Document Node: The root of the DOM tree representing the entire document.
Element Node: Represents an HTML or XML element (e.g., <div> , <span> ).
Text Node: Contains the text content within an element.
Attribute Node: Represents attributes of HTML elements, although attributes are not directly
accessed as nodes in the DOM.
Comment Node: Represents comments in the document.

Key Characteristics
Tree Structure: The DOM is structured as a hierarchical tree, where each node can have child
nodes. This structure allows for easy traversal and manipulation of the document.
Dynamic: The DOM is dynamic; it can be modified at any time through scripts. This means you
can add, remove, or change nodes after the page has loaded, which allows for creating interactive
web applications.
Event-Driven: The DOM is designed to handle events. Scripts can listen for events (like clicks,
keyboard input, etc.) and respond accordingly, making web pages interactive.

Accessing the DOM


The DOM is exposed to JavaScript through the document object, which acts as an entry point to
the DOM.
You can traverse the DOM tree using properties and methods provided by the document object,
allowing for both selection and manipulation of nodes.
Program:

DOM
1. document.getElementById(id)
Purpose: Selects a single element by its unique id .
Input: A string representing the id (e.g., 'header' ).
Output: Returns the element with the matching id or null if not found.
Example:

let element = document.getElementById('header'); // 'header' is a string

console.log(element); // Logs the element with id="header"

2. document.getElementsByClassName(className)
Purpose: Selects multiple elements that share the same class name.
Input: A string representing the class name (e.g., 'menu-item' ).
Output: Returns a live HTMLCollection (like an array but dynamic).
Example:

let elements = document.getElementsByClassName('menu-item'); // 'menu-item' is a string

console.log(elements); // Logs all elements with class="menu-item"

3. document.getElementsByTagName(tagName)
Purpose: Selects all elements with a specific tag (e.g., div , p , span ).
Input: A string representing the tag name (e.g., 'p' ).
Output: Returns a live HTMLCollection of elements.
Example:

let paragraphs = document.getElementsByTagName('p'); // 'p' is a string

console.log(paragraphs); // Logs all <p> (paragraph) elements


4. element.setAttribute(attribute, value)
Purpose: Adds or updates an attribute for an HTML element.
Input:

1. A string representing the attribute name (e.g., 'href' , 'src' ).


2. A string representing the value of the attribute (e.g., 'https://example.com' ).
Example:

let link = document.getElementById('myLink');

link.setAttribute('href','https://example.com'); // 'href' and the URL are strings

5. element.getAttribute(attribute)
Purpose: Retrieves the value of a specific attribute from an HTML element.
Input: A string representing the attribute name (e.g., 'id' , 'src' ).
Output: Returns the attribute value as a string or null if it doesn't exist.
Example:

let img = document.getElementById('myImage');

let srcValue = img.getAttribute('src'); // 'src' is a string

console.log(srcValue); // Logs the value of the 'src' attribute

1. innerHTML
Purpose: Represents the HTML content inside an element, including nested tags.
Usage: You can get or set the HTML content inside an element.
Output: Returns the HTML content as a string.
Example:
let div = document.getElementById('myDiv');

console.log(div.innerHTML); // Logs the entire HTML content, including tags

div.innerHTML = '<p>New <em>Content</em></p>'; // Sets new HTML content

2. innerText
Purpose: Represents the visible text inside an element (ignores hidden content).
Usage: You can get or set the visible text.
Excludes hidden elements: Ignores text inside elements with display: none or visibility:
hidden .

Output: Returns only the visible text as a string.


Example:

let div = document.getElementById('myDiv');

console.log(div.innerText); // Logs the visible text, ignoring hidden content

div.innerText = 'New Visible Text'; // Sets the visible text

3. textContent
Purpose: Represents the entire text content of an element, including hidden elements.
Usage: You can get or set all text content inside an element.
Includes hidden elements: Grabs text content even from hidden elements.
Output: Returns all text as a string.

Example:

let div = document.getElementById('myDiv');

console.log(div.textContent); // Logs all text content, including hidden text

div.textContent = 'All Text Content'; // Sets all text content


Comparison: innerHTML , innerText , and textContent
innerHTML : Includes HTML tags and can modify the structure of the content.

innerText : Only returns or sets visible text, excluding hidden content.

textContent : Returns or sets all text, including hidden content, but ignores HTML tags.

Example for Context (using provided HTML):

<h1 id="title" class="heading">

<span style="display: none;">test</span> Hello I am DOM


</h1>

innerHTML :

let title = document.getElementById('title');

console.log(title.innerHTML);

// Output: "<span style=\"display: none;\">test</span>Hello I am DOM"

innerText :

console.log(title.innerText); // Output: "Hello I am DOM" (ignores hidden 'test')

textContent :

console.log(title.textContent);

// Output: "testHello I am DOM" (includes hidden 'test')


Certainly! Here’s a concise explanation focusing on why NodeList
supports forEach , while HTMLCollection does not.

Key Differences: NodeList vs. HTMLCollection

NodeList
Contains: All types of nodes (HTML elements, text nodes, comments).
Live vs. Static:

Can be live (e.g., childNodes ) or static (e.g., querySelectorAll ).


Supports forEach :
Static NodeLists (like those from querySelectorAll ) support array
methods, including forEach .
Example:

let nodes = document.querySelectorAll('div'); // Static NodeList


nodes.forEach((node) => {
console.log(node.innerText); // Logs text of each <div>
});

HTMLCollection
Contains: Only HTML elements.
Always Live: Automatically updates with DOM changes.
Does Not Support forEach :

HTMLCollections do not have array methods like forEach .


To use array methods, you need to convert it to an array first.
Example:

let divs = document.getElementsByTagName('div'); // HTMLCollection


Array.from(divs).forEach((div) => {
console.log(div.innerText); // Logs text ofeach <div>
});
Summary
NodeList:

Supports forEach directly for static lists.


HTMLCollection:

Does not support forEach and requires conversion to an array to use such methods.

This brief overview explains why NodeList has forEach while HTMLCollection does not, focusing on
their characteristics and how they are used
Program:

1. Selecting the Parent Element

const parent = document.querySelector('.parent');

console.log(parent);
Explanation:
document.querySelector('.parent') : Selects the first element with the class parent .

console.log(parent) : Logs the selected element to the console.

Output:

<div class="parent">
<div class="day">Monday</div>
<div class="day">Tuesday</div>
<div class="day">Wednesday</div>
<div class="day">Thursday</div>
</div>

2. Accessing Children of the Parent

console.log(parent.children);

console.log(parent.children[1].innerHTML);

Explanation:
parent.children : Retrieves an HTMLCollection of the child elements of the parent .

parent.children[1].innerHTML : Logs the inner HTML of the second child ( Tuesday ).

Output:
parent.children :

HTMLCollection(4) [div.day, div.day, div.day, div.day]

parent.children[1].innerHTML (content of the second child):

Tuesday
3. Looping Through the Children

for (let i = 0; i < parent.children.length; i++) {

console.log(parent.children[i].innerHTML);

Explanation:
A for loop goes through each child of the parent and logs its innerHTML (text content).
Output (prints each child’s content):

Monday

Tuesday

Wednesday

Thursday

4. Modifying Child Element's Style

parent.children[1].style.color = "orange";

Explanation:
This changes the text color of the second child ( Tuesday ) to orange using inline CSS.
Effect on Webpage:
The text "Tuesday" will appear in orange.
No direct console output, but this change will be visible on the webpage.
5. Accessing First and Last Child Elements

console.log(parent.firstElementChild);

console.log(parent.lastElementChild);

Explanation:
parent.firstElementChild : Logs the first child of the parent ( Monday ).

parent.lastElementChild : Logs the last child of the parent ( Thursday ).

Output:
First Child ( Monday ):

<div class="day">Monday</div>

Last Child ( Thursday ):

<div class="day">Thursday</div>

6. Selecting the First .day Element

const dayOne = document.querySelector('.day');

console.log(dayOne);

Explanation:
document.querySelector('.day') : Selects the first element with the class day , which
is Monday .
console.log(dayOne) : Logs the first .day element.

Output:

<div class="day">Monday</div>
7. Accessing the Parent and Sibling of the First Day

console.log(dayOne.parentElement);

console.log(dayOne.nextElementSibling);

Explanation:
dayOne.parentElement : Logs the parent of dayOne , which is the .parent div .

dayOne.nextElementSibling : Logs the next sibling of dayOne , which is Tuesday .

Output:
Parent Element ( .parent div):

<div class="parent">
<div class="day">Monday</div>
<div class="day">Tuesday</div>
<div class="day">Wednesday</div>
<div class="day">Thursday</div>
</div>

Next Sibling ( Tuesday ):

<div class="day">Tuesday</div>

8. Accessing childNodes

console.log("NODES: ", parent.childNodes);


Explanation:
parent.childNodes : Logs all child nodes of the parent, including text nodes (spaces between
elements), which aren't shown by children .
childNodes includes all node types, whereas children only includes element nodes.

Output:
The childNodes output will show both element nodes ( div.day ) and text nodes (which
represent whitespace or line breaks):

NODES: NodeList(9) [text, div.day, text, div.day, text, div.day, text, div.day,
text]

Here, the text nodes represent spaces or line breaks between the div elements.

Summary:
Parent-Child Relationships: We can access the parent and
children using parentElement , children , and firstElementChild .
Accessing Content: We use innerHTML to get or modify the content of the child elements.
Modifying Style: You can dynamically modify the style of any child element (like changing text
color).
Navigating the DOM: We can move between parent, sibling, and child elements using properties
like nextElementSibling , firstElementChild , etc.
Difference between childNodes and children : childNodes contains all node types (including
text nodes), while children contains only the element nodes.
Program:

Why you shouldnot use className i have explain below


so use classList

Detailed Explanation of Code:


1. Creating a div Element:

const div = document.createElement('div');

This creates an empty div element that is not yet added to the DOM (i.e., not visible in the
document).
2. Logging the div to Console:

console.log(div);

This logs the newly created div element to the browser's console for debugging purposes.
3. Adding a Class Name to div :

div.className = "main";

This assigns the class name main to the div , which could later be used for styling in CSS.
4. Setting a Dynamic id :

div.id = Math.round(Math.random() * 10 + 1);

This sets the id of the div to a random number between 1 and 11 (rounded). The id is
generated dynamically.

In simple terms, Math.round(Math.random() * 10 + 1) does the following:


1. Math.random() generates a random decimal number between 0 and 1 (like 0.5, 0.8, etc.).
2. * 10 multiplies that number by 10, giving you a random number between 0 and 10 (like 5,
8, etc.).
3. + 1 adds 1 to shift the range, making the random number between 1 and 11 (so it never
returns 0).
4. Math.round() rounds the number to the nearest whole number (integer).

Result:
You get a random integer between 1 and 11.

5. Setting a title Attribute:

div.setAttribute("title", "generated title");

This assigns a title attribute to the div . When you hover


over the div , the text"generated title" will appear as a
tooltip.

6. Styling the div :

div.style.backgroundColor = "green"; div.style.padding = "12px";

These lines add inline styles to the div , making its background color green and
adding 12px of padding around it.
7. Creating a Text Node:

const addText = document.createTextNode("Hello World");

This creates a text node with the content "Hello World" . Text nodes are required to add
textual content to an element in a safe way.

8. Appending the Text Node to the div :

div.appendChild(addText);

This appends the created text node to the div , making "Hello World" appear as the
content inside the div .

9. Adding the div to the Document:

document.body.appendChild(div);

This appends the div to the body of the document, making it visible on the page.
NOTE: WHY you should use classList over className
className:
Purpose: Gets or sets all the classes of an HTML element as a single string.
Example:

element.className = "new-class"; // Replaces all existing classes

Downside: Overwrites all the existing classes when setting a new one.

classList:
Purpose: Provides methods to add, remove, and toggle individual classes without affecting
others.Handles individual classes using a list of tokens (via DOMTokenList).

Example:

element.classList.add('new-class'); // Adds a class


element.classList.remove('old-class'); // Removes a class
element.classList.toggle('active'); // Adds or removes a class

Advantages: Easier to use for manipulating individual classes and doesn't overwrite all classes.

Key Difference:
className manipulates the whole class string.
classList gives methods to work with each class separately, making it more flexible and safer for
multiple operations.
createTextNode() VS innerHTML

Key Differences in Behavior:


innerHTML and innerText :

Retrieve existing content, then overwrite it with the new content. Both replace any previous
content entirely.
innerHTML can handle both HTML and text, while innerText is strictly for plain text.

setAttribute() and createTextNode() :

Directly set values without retrieving or processing the previous content.


setAttribute() modifies an element’s attributes, while createTextNode() appends a text
node.

Why Prefer createTextNode() ?


Avoid Overwriting: When you use createTextNode() and appendChild() , you’re adding new
content without replacing existing elements or text.
Security: createTextNode() ensures that the inserted text is not parsed as HTML, which avoids
XSS vulnerabilities.
Granular Control: You can create, manipulate, and move text nodes in a more controlled way
without affecting other DOM elements.

In conclusion, innerHTML and innerText first retrieve the current content and then replace it with the
new value, while setAttribute() and createTextNode() directly modify or add specific
properties/text without retrieving or modifying other content in the element.
Program:
When you use innerHTML , the browser parses the string as HTML, and this process involves traversing
through the existing DOM to replace or modify the content. On the other hand, createTextNode
directly creates a text node and appends it to an element, avoiding unnecessary parsing and DOM
traversal. This makes createTextNode more optimal in termsof performance, especially in large projects
with frequent DOM updates.

Here’s an in-depth explanation of the code, with focus on performance and traversal:

Code Explanation in Detail

1. HTML Setup

<ul class="one">

<li>Java</li>

</ul>

A simple unordered list ( <ul> ) is initialized with one item ( <li>Java</li> ). We'll dynamically
add, edit, and remove list items using JavaScript.

2. Function addLang

function addLang(langName) {
const li = document.createElement('li');
li.innerHTML =`${langName}`;
document.querySelector('.one').appendChild(li);
}

addLang("Python");

addLang("TypeScript");

What it does: This function adds new <li> elements with the langName passed to it. It
uses innerHTML to add text.
How innerHTML works:

Parsing and Traversal: When you set innerHTML , the browser parses the string as HTML,
traverses the DOM to locate the target element, and then replaces or appends the content.
Performance issue: Every time you call addLang , the browser needs to parse the string as
HTML, which involves DOM traversal and can be costly in terms of performance, especially in
large-scale applications with frequent updates.

3. Function addLangOpti

function addLangOpti(langName) {
const li = document.createElement('li');
const addtext = document.createTextNode(langName);
li.appendChild(addtext);
document.querySelector('.one').appendChild(li);
}

addLangOpti("JavaScript");
addLangOpti("C++");

What it does: This function also adds a new <li> , but it uses createTextNode instead
of innerHTML .
How createTextNode works:

Direct Node Creation: createTextNode creates a plain text node and directly adds it to the
DOM without parsing it as HTML. This avoids unnecessary parsing and DOM traversal.
Better performance: Since there's no HTML parsing, createTextNode is faster and more
efficient, particularly in large projects. The browser doesn’t need to traverse the DOM
unnecessarily.
Summary: In large applications, createTextNode is more optimal than innerHTML because it
avoids costly DOM traversal and parsing.
4. Editing List Items

Changing the Second List Item:

const secondlang = document.querySelector('li:nth-child(2)');


secondlang.textContent ="C#";

What it does: Selects the second <li> and changes its text to "C#" .
Using textContent : This method replaces the content inside the <li> element without any
parsing, which is faster than innerHTML .

Replacing the Third List Item:

const newLang = document.createElement('li');


newLang.textContent = "Mojo";
document.querySelector('li:nth-child(3)').replaceWith(newLang);

What it does: Creates a new <li> with the text "Mojo" and replaces the third item in the list.
Efficiency: This is a clean way to replace elements without unnecessary parsing or traversal.

Changing the Fifth List Item:

const fifthLang = document.querySelector('li:nth-child(5)');


fifthLang.outerHTML = "<li>PHP</li>";

What it does: Replaces the fifth list item using outerHTML .

Issue with outerHTML : Similar to innerHTML , outerHTML parses the string as HTML, which
involves DOM traversal and can slow down performance.
5. Removing the Last Item

const lastLang = document.querySelector('li:last-child');


lastLang.remove();

What it does: Selects and removes the last list item from the DOM.
Efficient: This is an efficient method to remove elements, as it directly modifies the DOM without
any unnecessary operations.

Key Points: innerHTML vs createTextNode


1. innerHTML :
What happens:

When you use innerHTML , the browser parses the string as HTML and traverses the
DOM to update the structure.
This process is repeated every time you use innerHTML , which can lead to performance
issues in large-scale projects.
Performance: Parsing and traversing the DOM every time slows down the browser, especially
when working with a lot of dynamic content.
2. createTextNode :
What happens:

createTextNode directly creates a text node and appends it to an element without


parsing HTML. The text is treated purely as content, not as code.
The browser does not need to traverse or reparse the DOM.
Performance: This is much more efficient and secure. It avoids unnecessary DOM traversal
and parsing overhead, making it ideal for large projects or frequent updates.
Summary Note
Parsing and Traversing:

innerHTML requires parsing the string as HTML and traversing the DOM to update or replace
the content, which introduces extra overhead.
createTextNode avoids HTML parsing and DOM traversal by directly creating and appending
text nodes, making it faster and more efficient, especially in large projects.
When to Use:

Use createTextNode or textContent when you only need to manipulate plain text. This
avoids the performance hit from HTML parsing and is more secure since no HTML is
processed.
innerHTML is suitable for small, simple tasks where HTML structure needs to be modified, but
it’s less optimal for complex applications with frequent dynamic content changes.

By using createTextNode , you improve performance and security, especially when working with
larger applications where efficiency matters.

You might also like