The HTML DOM (Document Object Model) allows JavaScript to dynamically access and manipulate HTML elements. Here are a variety of examples demonstrating how to use JavaScript with the HTML DOM.
1. Change Text Content
document.getElementById("demo").innerHTML = "Hello, JavaScript!";
HTML:
<p id="demo">Original Text</p>
This replaces the content of the <p>
element with new text.
2. Change Style
document.getElementById("demo").style.color = "blue";
HTML:
<p id="demo">Change my color!</p>
This example modifies the color of the text.
3. Add an Event Listener
document.getElementById("myButton").addEventListener("click", () => {
alert("Button clicked!");
});
HTML:
<button id="myButton">Click Me!</button>
This example attaches a click event to the button.
4. Hide an Element
document.getElementById("demo").style.display = "none";
HTML:
<p id="demo">This will disappear.</p>
This hides the <p>
element when the script runs.
5. Show an Element
document.getElementById("demo").style.display = "block";
HTML:
<p id="demo" style="display:none;">Now you see me!</p>
This makes a hidden element visible.
6. Add and Remove Classes
Add a CSS class:
document.getElementById("demo").classList.add("highlight");
Remove a CSS class:
document.getElementById("demo").classList.remove("highlight");
HTML:
<p id="demo" class="normal">I can be styled dynamically.</p>
7. Create a New Element
let newElement = document.createElement("p");
newElement.innerHTML = "I am a new paragraph.";
document.body.appendChild(newElement);
This example creates a new paragraph and adds it to the document.
8. Remove an Element
let element = document.getElementById("demo");
element.parentNode.removeChild(element);
HTML:
<p id="demo">Goodbye!</p>
This removes the specified element from the DOM.
9. Access Form Input Values
let inputValue = document.getElementById("nameInput").value;
console.log(inputValue);
HTML:
<input type="text" id="nameInput" value="John Doe">
This retrieves the value of a form input field.
10. Modify Attributes
document.getElementById("link").setAttribute("href", "https://www.google.com");
HTML:
<a id="link" href="#">Original Link</a>
This changes the href
attribute of the anchor tag.
11. Traverse the DOM
Access Child Nodes
let children = document.getElementById("parent").children;
console.log(children);
HTML:
<div id="parent">
<p>Child 1</p>
<p>Child 2</p>
</div>
This retrieves all child nodes of the div
with ID parent
.
12. Dynamic HTML Table
let table = document.createElement("table");
for (let i = 0; i < 3; i++) {
let row = table.insertRow();
for (let j = 0; j < 3; j++) {
let cell = row.insertCell();
cell.innerHTML = `Row ${i + 1}, Cell ${j + 1}`;
}
}
document.body.appendChild(table);
This generates a 3×3 HTML table dynamically.
Explore More
Discover more interactive DOM examples at The Coding College. These examples can be directly used or customized for your projects!