Select elements
To work with an element, first you have to find it. The most used methods are:
document.getElementById("title"); // by id
document.querySelector(".notice"); // first element matching the CSS selector
document.querySelectorAll("li"); // ALL that match (list)
querySelector accepts any CSS selector: "#id", ".class",
"div > p", etc. It is the most flexible option and the recommended one nowadays.
Change the content
const title = document.querySelector("h1");
title.textContent = "New title"; // changes the text (safe)
title.innerHTML = "<em>Hello</em>"; // interprets HTML (careful with user data)
textContent: treats everything as plain text. It is the safe option.innerHTML: interprets HTML tags. Useful, but dangerous if the content comes from the user (risk of code injection).
Change attributes and styles
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
link.classList.add("active"); // add CSS class
link.classList.remove("hidden");
link.style.color = "red"; // inline style
To build HTML as text (what you will do in the exercises), template strings are enough:
const name = "Ana";
const greeting = `<p>Hello, ${name}</p>`;
console.log(greeting); // "<p>Hello, Ana</p>"
Examples
Build HTML as text with a template
function card(title, text) {
return `<div class="card"><h2>${title}</h2><p>${text}</p></div>`;
}
console.log(card("Hello", "Welcome"));