6️⃣ Handling Events
Events allow JavaScript to respond to user actions.
Common events include:
• click, When an element is clicked.
• mouseover, When the pointer moves over an element.
• mouseout, When the pointer leaves an element.
• keydown, When a keyboard key is pressed.
• submit, When a form is submitted.
• change, When an input value changes.
<button id="btn">Click Me</button>
let button = document.getElementById("btn");
button.addEventListener("click", function() {
console.log("Button Clicked!");
});
Whenever the user clicks the button, the message appears in the console.
7️⃣ Creating New HTML Elements
JavaScript can create HTML elements dynamically.
let paragraph = document.createElement("p");
paragraph.textContent = "This is a new paragraph.";
document.body.appendChild(paragraph);
Here:
• createElement() creates a new element.
• textContent adds its text.
• appendChild() inserts it into the page.
8️⃣ Removing HTML Elements
You can remove elements using remove().
<p id="text">Remove this paragraph</p>
let paragraph = document.getElementById("text");
paragraph.remove();
The paragraph will be removed from the webpage.
9️⃣ Working with Input Fields
JavaScript can read values entered by users.
<input type="text" id="username" placeholder="Enter your name">
<button id="submit">Submit</button>
let button = document.getElementById("submit");
button.addEventListener("click", function() {
let name = document.getElementById("username").value;
console.log("Welcome " + name);
});
The .value property retrieves the current value of an input field.
🔟 DOM Traversal
DOM traversal means moving between related HTML elements.
Some useful properties:
• parentElement, Gets the parent element.
• children, Gets the child elements.
• firstElementChild, Gets the first child element.
• lastElementChild, Gets the last child element.
• nextElementSibling, Gets the next sibling.
• previousElementSibling, Gets the previous sibling.
<div id="parent">
<p>First</p>
<p>Second</p>
</div>
let parent = document.getElementById("parent");
console.log(parent.children);
console.log(parent.firstElementChild);
1️⃣1️⃣ Event Object
When an event occurs, JavaScript provides an event object containing information about that event.
button.addEventListener("click", function(event) {
console.log(event.type);
console.log(event.target);
});
Output:
click
<button id="btn">Click Me</button>
Some useful event properties:
• event.type, Type of event.
• event.target, Element that triggered the event.
• event.preventDefault(), Prevents the browser's default action.
1️⃣2️⃣ Event Bubbling
Event bubbling means an event triggered on a child element can propagate upward to its parent elements.
For example:
<div id="parent">
<button id="child">Click Me</button>
</div>