JavaScript HTML DOM
Manipulate HTML elements with JavaScript
🌐 What is the DOM?
The DOM (Document Object Model) is how JavaScript can access and change HTML elements on a web page. Think of it as a bridge between JavaScript and HTML.
// Access an element by ID
let element = document.getElementById("myElement");
element.innerHTML = "New content!";
Finding HTML Elements
By ID
Find element with specific ID
let element = document.getElementById("myId");
By Tag Name
Find elements by tag
let paragraphs = document.getElementsByTagName("p");
By Class Name
Find elements by CSS class
let items = document.getElementsByClassName("item");
Query Selector
Find using CSS selectors
let element = document.querySelector(".myClass");
🔹 Changing HTML Content
Modify text and HTML inside elements:
🔸 innerHTML Example
<p id="content">Original content</p>
<button onclick="changeContent()">Change Content</button>
<script>
function changeContent() {
document.getElementById("content").innerHTML = "<strong>New bold content!</strong>";
}
</script>
Try it:
Original content
🔹 Changing HTML Attributes
Modify element attributes like src, href, class, etc.:
<img id="myImage" src="image1.jpg" alt="Image">
<button onclick="changeImage()">Change Image</button>
<script>
function changeImage() {
document.getElementById("myImage").src = "image2.jpg";
document.getElementById("myImage").alt = "New Image";
}
</script>
Try it:
🔹 Changing CSS Styles
Modify element appearance with JavaScript:
<p id="styleDemo">This text will change style</p>
<button onclick="changeStyle()">Change Style</button>
<script>
function changeStyle() {
let element = document.getElementById("styleDemo");
element.style.color = "red";
element.style.fontSize = "20px";
element.style.fontWeight = "bold";
}
</script>
Try it:
This text will change style
🔹 Adding and Removing Elements
Create new elements or remove existing ones:
🔸 Adding Elements
// Create new element
let newParagraph = document.createElement("p");
newParagraph.innerHTML = "This is a new paragraph";
// Add to page
document.body.appendChild(newParagraph);
🔸 Removing Elements
// Remove element by ID
let element = document.getElementById("removeMe");
element.remove();
Try it:
This element can be removed
🔹 Working with Forms
Access and modify form elements:
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="getName()">Get Name</button>
<p id="result"></p>
<script>
function getName() {
let name = document.getElementById("nameInput").value;
document.getElementById("result").innerHTML = "Hello, " + name + "!";
}
</script>
Try it: