DevPath · Learn to code ESPTEN

The DOM and Events

Select and modify elements

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)

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"));
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← What is the DOM?Events and forms →