DOM Elements
DOM elements represent the building blocks of a webpage, corresponding to HTML tags such as <div>
, <h1>
, and <p>
. JavaScript provides methods to create, access, and manipulate these elements dynamically.
Key Topics
Accessing Elements
You can use methods like getElementById
, getElementsByClassName
, and querySelector
to retrieve specific elements from the DOM.
const heading = document.getElementById("header");
console.log(heading.textContent);
Output
> Logs the text content of the element with id "header".
Explanation: The getElementById
method retrieves an element by its ID, enabling access to its properties and content.
Creating Elements
Use the createElement
method to dynamically create new elements and append them to the DOM using appendChild
or insertBefore
.
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
appends it to the DOM.
Modifying Elements
Elements can be modified by changing their attributes, styles, and content using methods like setAttribute
, innerHTML
, and classList
.
const element = document.getElementById("header");
element.textContent = "Updated Heading";
element.style.color = "blue";
Output
(The heading text is updated, and its color changes to blue.)
Explanation: The textContent
property updates the element's text, and the style
property modifies its CSS.
JavaScript Usage in DOM
Below is a complete DOM example showcasing element creation and modification dynamically.
<!DOCTYPE html>
<html>
<head>
<title>DOM Elements Example</title>
</head>
<body>
<button onclick="addElement()">Add Element</button>
<div id="container"></div>
<script>
function addElement() {
const newDiv = document.createElement("div");
newDiv.textContent = "This is a dynamically added div.";
newDiv.style.backgroundColor = "lightgray";
document.getElementById("container").appendChild(newDiv);
}
</script>
</body>
</html>
Key Takeaways
- Access Elements: Use methods like
getElementById
andquerySelector
to retrieve elements. - Create Elements: Use
createElement
andappendChild
to add elements dynamically. - Modify Elements: Update attributes, styles, and content using JavaScript.
- DOM Integration: Use DOM manipulation to build interactive and dynamic webpages.