JavaScript Tutorial · JavaScript in the Browser · Lesson 41 of 44
JavaScript DOM Manipulation
Create, insert and remove elements; change classes, styles and attributes.
Creating elements
document.createElement() makes a new element; append() adds it to the page:
<ul id="list"></ul>
<script>
const list = document.getElementById("list");
for (const lang of ["HTML", "CSS", "JavaScript"]) {
const li = document.createElement("li");
li.textContent = lang;
list.append(li);
}
const note = document.createElement("p");
note.textContent = `The list has ${list.children.length} items.`;
list.after(note);
</script>
Classes, styles and attributes
el.classList.add/remove/toggle("name")— the best way to change styling (keep the styles in CSS).el.style.color = "red"— inline styles for one-off values.el.setAttribute("href", url),el.dataset.id— attributes anddata-*attributes.
<style>
.card { padding: 12px; border: 1px solid #ccc; border-radius: 8px; font-family: sans-serif; }
.highlight { background: #fff3c4; border-color: #e0b400; }
</style>
<div class="card" id="card" data-user-id="42">Card for user</div>
<script>
const card = document.getElementById("card");
card.classList.add("highlight");
card.textContent += ` #${card.dataset.userId}`;
card.style.fontWeight = "bold";
card.setAttribute("title", "I have a tooltip");
</script>
Removing elements
el.remove() removes an element from the page.
Test yourself
Which property toggles a CSS class on an element?
className.toggleclassListstyle.classcssClass
Show answer
Answer: classList