JavaScript & DOM Manipulation
Introduction to JavaScript
• JavaScript is a powerful scripting language used to add interactivity to websites.
• It interacts with the DOM (Document Object Model) to dynamically update HTML
and CSS.
• In this presentation, we'll explore 10 core DOM manipulation concepts.
// Example: Basic JS Function
function greet() {
alert('Welcome to DOM Learning!');
}
What is the Document Object
Model (DOM)?
• DOM represents an HTML page as a tree-like structure of objects.
• Each HTML tag is an element (node) that can be accessed and modified using
JavaScript.
• Think of DOM as a live interface between JS and the webpage.
// Accessing the document root
[Link](document);
// Accessing the body element
[Link]([Link]);
Accessing Elements
• To manipulate HTML elements, you must first access them.
• Methods: getElementById, getElementsByClassName, querySelector,
querySelectorAll.
// Examples:
[Link]('demo');
[Link]('text')[0];
[Link]('#idName');
[Link]('.className');
Changing Content
• You can update text or HTML content dynamically.
• innerText, innerHTML, and textContent are three main properties used.
[Link]('demo').innerText = 'Hello!';
[Link]('demo').innerHTML = '<b>Hello Bold!</b>';
[Link]('demo').textContent = 'Plain text only';
Changing Styles
• Modify an element's CSS directly using the style property.
• Useful for animations and visual effects.
let para = [Link]('demo');
[Link] = 'red';
[Link] = '24px';
[Link] = 'yellow';
Creating Elements
• Create new HTML elements and attach them to the DOM using createElement()
and appendChild().
let newDiv = [Link]('div');
[Link] = 'This is new content!';
[Link](newDiv);
Appending and Removing
Elements
• Add or remove nodes programmatically.
let parent = [Link]('list');
let li = [Link]('li');
[Link] = 'New Item';
[Link](li); // Add
[Link]([Link]); // Remove
Event Handling
• Handle user interactions like clicks, mouseovers, and keypresses using
addEventListener().
[Link]('btn').addEventListener('click', function() {
alert('Button clicked!');
});
Traversing the DOM
• Navigate the DOM structure using parent, child, and sibling relationships.
let child = [Link]('child');
[Link]([Link]); // Access parent
[Link]([Link]); // Next element