0% found this document useful (0 votes)
6 views

Javascript-DOM-Manipulation

The document provides an overview of JavaScript DOM manipulation, explaining the Document Object Model (DOM) as an interface for interacting with HTML/XML documents. It covers methods for accessing and modifying the DOM, event handling, and best practices for writing maintainable code. Additionally, it includes examples of creating and removing elements, as well as practice questions for further learning.

Uploaded by

asfa rehman
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Javascript-DOM-Manipulation

The document provides an overview of JavaScript DOM manipulation, explaining the Document Object Model (DOM) as an interface for interacting with HTML/XML documents. It covers methods for accessing and modifying the DOM, event handling, and best practices for writing maintainable code. Additionally, it includes examples of creating and removing elements, as well as practice questions for further learning.

Uploaded by

asfa rehman
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

JAVASCRIPT DOM

MANIPULATION
JavaScript DOM Manipulation

What is the DOM?


DOM (Document Object Model) is an interface that allows
programs (like JavaScript) to interact with and manipulate
HTML/XML documents.

Analogy: Think of the DOM as a tree structure where every


HTML element is a node that can be accessed and modified.
Why is it important?

•Enables dynamic content updates (without reloading the page).


•Provides interaction with the webpage (e.g., responding to user
input).
Example
<!DOCTYPE HTML>
<html>
<head>
<title>About elk</title>
</head>
<body>
The truth about elk.
</body>
</html>
How to access the DOM?
Document Object: The document object is the root node and entry point for
accessing the DOM.
Selecting Elements:

Old methods:
•document.getElementById()
•document.getElementsByClassName()
Modern methods:
•document.querySelector() (first matching element)
•document.querySelectorAll() (all matching elements)
How to access the DOM?
How to access the DOM?

document.querySelector():
Use this when you want to select the first element that matches a CSS
selector. It’s much more flexible since you can select by any CSS selector
but will return only one element.

document.querySelectorAll():
Use this when you need to select all matching elements using a CSS selector.
It’s the most versatile method for selecting multiple elements but returns a
static NodeList.
document.querySelector()

<!DOCTYPE html>
<html> <script>
<head> // Selects the first element with the class 'intro'
<title>querySelector Example</title> let firstIntro = document.querySelector('.intro');
</head> console.log(firstIntro);
<body> </script>
<h1>Heading 1</h1> </body>
<h2>Heading 2</h2> </html>
<p class="intro">First paragraph</p>
<p class="intro">Second paragraph</p>

Output: <p class="intro">First paragraph</p>


document.querySelectorAll()

<!DOCTYPE html> <script>


<html> // Selects all elements with the class 'intro’
<head> let allIntroElements = document.querySelectorAll('.intro');
<title>querySelectorAll Example</title> allIntroElements.forEach(element => {
</head> console.log(element);
<body> });
<h1>Heading 1</h1> </script>
<h2>Heading 2</h2> </body>
<p class="intro">First paragraph</p> </html>
<p class="intro">Second paragraph</p>
Output:
<p class="intro">First paragraph</p>
<p class="intro">Second paragraph</p>
Let’s practice this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Test Page</title>
</head>
<body>
<h1>Test Page</h1>
<p id="para">This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Output
Before:

After:
Modify DOM
1. Changing Content: innerHTML vs textContent
Example:
document.getElementById('header').textContent = 'New Heading’;

2. Modifying Attributes: setAttribute(), getAttribute(), removeAttribute()


Example:
document.querySelector('img').setAttribute('src', 'newImage.jpg’);

3. Changing Styles: Use style property or classList to change CSS


dynamically.
Example:
document.querySelector('.box').style.backgroundColor = 'blue';
Modify DOM
Modify DOM Example
<div id="demo">
<p>This is <strong>bold</strong> text.</p>
</div>

<script>
// Using innerHTML
console.log(document.getElementById('demo').innerHTML);
// Output: <p>This is <strong>bold</strong> text.</p>

// Using textContent
console.log(document.getElementById('demo').textContent);
// Output: This is bold text.
</script>
Event Handling
What are events?
Browser events like clicks, keypresses, mouseovers.

Old way:
Inline event handlers (e.g., onclick) or setting element.onclick.
Modern way:
addEventListener() method: flexible and doesn't overwrite existing
handlers.

document.querySelector('button').addEventListener('click', function() {
alert('Button clicked!');
});
Event Handling
Inline Event Handler
<!DOCTYPE html>
<html lang="en">
<head>
<title>Inline Event Handler Example</title>
</head>
<body>
<button onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>
addEventListener()
<!DOCTYPE html>
<html lang="en">
<head>
<title>addEventListener Example</title> // Attaching another event listener
</head>
<body> document.getElementById('myButton').addEven
<button id="myButton">Click Me</button> tListener('click', function() {
console.log('Another event handler');
<script> });
// Attaching event listener using addEventListener </script>
</body>
document.getElementById('myButton').addEventList </html>
ener('click', function() {
alert('Button clicked!');
});
Creating & Removing
Elements
Creating new elements:
createElement() and append()

let newDiv = document.createElement('div');


newDiv.textContent = 'New Div';
document.body.append(newDiv);
Creating & Removing
Elements

Removing elements:
Remove()

let element = document.querySelector('.item');


element.remove();
Best Practices

1. Use querySelector and addEventListener for more flexible and


maintainable code.
2. Avoid using innerHTML for user input to prevent XSS (Cross-site
Scripting) attacks.
3. Organize code for readability: keep JavaScript separate from HTML
(i.e., avoid inline JS).
Practice Questions

1. Change the color of a heading on click.


2. Dynamically add a list item when a button is clicked.
3. Go to the "Console" tab and play with the JavaScript code by
typing commands to create or remove elements manually,
observing changes in real time.

You might also like