Javascript-DOM-Manipulation
Javascript-DOM-Manipulation
MANIPULATION
JavaScript DOM Manipulation
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>
After:
Modify DOM
1. Changing Content: innerHTML vs textContent
Example:
document.getElementById('header').textContent = 'New Heading’;
<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()
Removing elements:
Remove()