JavaScript · JS HTML DOM · Lesson 48
DOM Changing HTML
Change content, attributes and create elements.
The HTML DOM allows JavaScript to change the content and attributes of HTML elements, and to create or remove elements.
Example
<img id="photo" src="https://picsum.photos/id/1011/200/120" alt="Lake">
<ul id="list"><li>First</li></ul>
<button onclick="change()">Change</button>
<script>
function change() {
document.getElementById("photo").src = "https://picsum.photos/id/1025/200/120";
document.getElementById("photo").setAttribute("alt", "Dog");
const li = document.createElement("li");
li.textContent = "Added at " + new Date().toLocaleTimeString();
document.getElementById("list").appendChild(li);
}
</script>
| Code | Does |
|---|---|
| element.innerHTML = ... | Change the content |
| element.attribute = ... | Change an attribute value |
| element.setAttribute(name, value) | Set any attribute |
| document.createElement(tag) | Create an element |
| parent.appendChild(el) / el.remove() | Add / remove an element |
Keep reading “DOM Changing HTML”
Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.