DOM Methods
DOM methods are functions provided by the Document Object Model that allow developers to interact with and manipulate HTML elements dynamically. These methods enable tasks like selecting, creating, updating, and removing elements.
Key Topics
Selecting Elements
DOM methods like getElementById
, querySelector
, and getElementsByClassName
allow you to select specific elements in the document.
const element = document.getElementById("demo");
console.log(element.textContent);
Output
> (Logs the text content of the element with id "demo".)
Explanation: The getElementById
method retrieves an element by its ID, allowing you to access and manipulate its properties.
Creating Elements
You can create new elements dynamically using methods like createElement
and appendChild
.
const newElement = document.createElement("p");
newElement.textContent = "This is a new paragraph.";
document.body.appendChild(newElement);
Output
(A new paragraph is added to the document body.)
Explanation: The createElement
method creates a new element, and appendChild
adds it to the document.
Modifying Elements
Methods like setAttribute
, removeAttribute
, and classList
allow you to modify an element's attributes, classes, and content dynamically.
const element = document.getElementById("demo");
element.setAttribute("style", "color: red;");
Output
(The text color of the element with id "demo" changes to red.)
Explanation: The setAttribute
method modifies the style
attribute of the selected element.
JavaScript Usage in DOM
Below is a complete DOM example demonstrating the use of methods to dynamically add and update elements.
<!DOCTYPE html>
<html>
<head>
<title>DOM Methods Example</title>
</head>
<body>
<button onclick="addElement()">Add Element</button>
<div id="container"></div>
<script>
function addElement() {
const newDiv = document.createElement("div");
newDiv.textContent = "Newly added div.";
document.getElementById("container").appendChild(newDiv);
}
</script>
</body>
</html>
Key Takeaways
- Selection: Use methods like
getElementById
andquerySelector
to select elements. - Creation: Dynamically create elements using
createElement
. - Modification: Update attributes, styles, and classes using DOM methods.
- DOM Integration: Enhance interactivity by dynamically manipulating elements in the DOM.