Changing the page
Once you've selected an element, you can change almost anything about it.
Text and HTML
HTML
<h2 id="title">Old title</h2>
<p id="info"></p>
<script>
document.querySelector("#title").textContent = "New title";
document.querySelector("#info").innerHTML = "Some <strong>bold</strong> text";
</script>textContentsets plain text, which is safe for any value.innerHTMLparses HTML. Never put text typed by users intoinnerHTML: it could contain a malicious<script>or image tag. UsetextContentfor user text.
Attributes
HTML
<img id="pic" src="https://picsum.photos/seed/a/240/120" alt="A picture">
<a id="link" href="#">A link</a>
<script>
const img = document.querySelector("#pic");
img.src = "https://picsum.photos/seed/b/240/120";
img.alt = "A different picture";
const link = document.querySelector("#link");
link.setAttribute("href", "https://developer.mozilla.org");
link.textContent = "MDN Web Docs";
console.log(link.getAttribute("href"));
</script>Classes
Toggling CSS classes is the cleanest way to change how something looks:
HTML
<style>
.card { padding: 14px; border: 2px solid #ccd; border-radius: 10px; font-family: system-ui; }
.card.active { border-color: #5a48f5; background: #efedff; }
</style>
<div class="card" id="c">Click the button to toggle me</div>
<button id="toggle">Toggle</button>
<script>
const card = document.querySelector("#c");
document.querySelector("#toggle").addEventListener("click", () => {
card.classList.toggle("active");
console.log("active?", card.classList.contains("active"));
});
</script>classList has add, remove, toggle and contains.
Inline styles
HTML
<p id="note">Watch me change</p>
<script>
const note = document.querySelector("#note");
note.style.color = "white";
note.style.backgroundColor = "#0aa9cf"; // CSS names become camelCase
note.style.padding = "10px";
</script>Creating and removing elements
HTML
<ul id="list"></ul>
<button id="add">Add item</button>
<button id="clear">Clear</button>
<script>
const list = document.querySelector("#list");
let n = 0;
document.querySelector("#add").addEventListener("click", () => {
const li = document.createElement("li");
li.textContent = `Item ${++n}`;
li.addEventListener("click", () => li.remove()); // click an item to remove it
list.append(li);
});
document.querySelector("#clear").addEventListener("click", () => {
list.replaceChildren();
});
</script>createElement makes an element, append adds it to the page, and remove takes it away.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.