The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.
- By ID: Use
getElementById()
. - By Class Name: Use
getElementsByClassName()
. - By Tag Name: Use
getElementsByTagName()
. - By Query Selector (single element): Use
querySelector()
. - By Query Selector All (multiple elements): Use
querySelectorAll()
.
Event delegation is a technique in JavaScript where you add a single event listener to a parent element, rather than adding multiple event listeners to individual child elements. When an event occurs on a child element, the event bubbles up (propagates) to the parent element, where it can be captured and handled.
It is Useful for:
- Performance: Instead of attaching event listeners to every child element (which can be inefficient for large or dynamic content), a single event listener on the parent can manage all events.
- Dynamic Elements: It allows handling of events for dynamically added elements without needing to reassign event listeners each time an element is added to the DOM.
- Cleaner Code: Managing events through the parent element leads to more maintainable and less redundant code.
- getAttribute() : Retrieves the value of a specified attribute.
- setAttribute() : Sets or changes the value of an attribute.
- removeAttribute() : Removes an attribute from an element.