DOM Events
DOM Events
DOM -->
Key Points:
let elements =
document.getElementsByClassName("className");
- getElementsByTagName: Retrieves elements by their tag
name. Returns an HTMLCollection.
console.log(element.textContent);
- getAttribute and setAttribute: Gets or sets the value of
an attribute on an element.
let id = element.getAttribute("id");
element.setAttribute("id", "newId");
element.style.backgroundColor = "blue";
Removing Elements:
element.remove();
### 5. Managing Classes
classList Property:
- add: Adds a class to an element.
- remove: Removes a class from an element.
- toggle: Toggles a class (adds if not present, removes if
present).
- contains: Checks if an element has a specific class.
Example:
element.classList.add("newClass");
element.classList.remove("oldClass");
element.classList.toggle("active");
console.log(element.classList.contains("newClass"));
#### addEventListener()
- Used to attach event handlers to elements.
- Syntax: element.addEventListener(event,
callbackfunction).
- event: The type of event (e.g., click, submit).
- callbackfunction: The function to be called when the
event occurs.
element.addEventListener('click', () => {
console.log('Element clicked');
});
#### Event Object
When an event occurs, an Event object is automatically
passed to the event handler. This object contains details
about the event:
- event.type: The type of the event (e.g., click).
- event.target: The element that triggered the event.
- event.preventDefault(): Prevents the default action
(e.g., stopping a form submission).
- event.stopPropagation(): Stops the event from bubbling
up to parent elements.
button.addEventListener('click', function(event) {
console.log(event.type); // "click"
event.preventDefault(); // Stops the default
behavior
});