JavaScript with DOM (Document Object Model)
The Document Object Model (DOM) allows JavaScript to access, modify, and manipulate HTML and CSS dynamically.
1️⃣ Accessing Elements in the DOM
JavaScript provides several methods to select elements.
📌 getElementById()
– Select by ID
🔹 Selects an element using its id
.
📌 getElementsByClassName()
– Select by Class
🔹 Returns a collection (HTMLCollection) of elements.
📌 getElementsByTagName()
– Select by Tag Name
🔹 Selects all elements of a given tag name.
📌 querySelector()
– Select the First Match
🔹 Selects the first matching element using CSS selectors.
📌 querySelectorAll()
– Select All Matches
🔹 Returns a NodeList (array-like) of all matching elements.
2️⃣ Changing & Modifying Elements
📌 Changing HTML Content (innerHTML
)
📌 Changing Text (innerText
/ textContent
)
📌 Changing CSS Styles (style
property)
📌 Changing Attributes (setAttribute
)
📌 Getting Attributes (getAttribute
)
3️⃣ Adding & Removing Elements
📌 Creating a New Element
📌 Removing an Element
📌 Replacing an Element
4️⃣ Handling Events in JavaScript
Events allow us to execute JavaScript when users interact with the webpage.
📌 Example: Click Event
📌 Mouse Events
📌 Keyboard Events
5️⃣ Traversing the DOM
You can navigate between elements using parent-child relationships.
📌 Parent Node
📌 Child Nodes
📌 Sibling Nodes
6️⃣ Full Example: JavaScript DOM in Action
Summary
Method | Description |
---|---|
getElementById(id) | Selects an element by ID. |
getElementsByClassName(class) | Selects elements by class (HTMLCollection). |
getElementsByTagName(tag) | Selects elements by tag name (HTMLCollection). |
querySelector(css) | Selects the first matching element. |
querySelectorAll(css) | Selects all matching elements (NodeList). |
innerHTML | Changes HTML content inside an element. |
innerText / textContent | Changes the text inside an element. |
style.property | Changes CSS styles dynamically. |
setAttribute(name, value) | Sets an attribute of an element. |
addEventListener(event, function) | Listens for user events (click, hover, keypress, etc.). |
Now you’re ready to manipulate the DOM like a pro! 🚀
Let me know if you have any questions! 😃