Tutorials / JavaScript Fundamentals / The DOM: selecting and changing elements

The DOM: selecting and changing elements

15 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. Project: build a to-do list in the browser

What the DOM is

When a browser loads an HTML page, it turns the tags into a tree of objects in memory. This tree is the Document Object Model, or DOM. JavaScript can read this tree and change it, and the page updates on screen straight away.

The entry point is the global document object. You can try everything here in the browser console on any page. For a file of your own, use this starter page:

<!DOCTYPE html>
<html>
  <body>
    <h1 id="title">Hello</h1>
    <ul id="list">
      <li class="item">One</li>
      <li class="item">Two</li>
    </ul>
    <script src="app.js"></script>
  </body>
</html>

The script is at the end of body so the elements exist when the code runs. If you put it in head, document.querySelector would find nothing, because the page is not built yet.

Selecting elements

The modern way is querySelector, which takes a CSS selector.

const title = document.querySelector("#title");        // by id
const firstItem = document.querySelector(".item");     // first with class
const allItems = document.querySelectorAll(".item");   // all matches

console.log(title.textContent);   // "Hello"
console.log(allItems.length);     // 2

querySelector returns one element, or null if nothing matches. querySelectorAll returns a list that you can loop with for...of or forEach. If you know CSS selectors, you already know how to select.

Changing content

title.textContent = "Welcome to my page";

textContent sets plain text. There is also innerHTML, which parses HTML:

title.innerHTML = "Welcome, <em>friend</em>";

Be careful with innerHTML. If you insert text that came from a user, they can inject a <script> or other markup and attack your visitors. That is called cross-site scripting (XSS). For anything that is not your own fixed markup, use textContent.

Changing styles and classes

You can set inline styles directly, but a better habit is to toggle CSS classes and keep the look in your stylesheet.

title.style.color = "tomato";           // inline style

title.classList.add("highlight");
title.classList.remove("highlight");
title.classList.toggle("highlight");    // add if missing, remove if present
console.log(title.classList.contains("highlight")); // true

Attributes

const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
console.log(link.getAttribute("href"));
link.removeAttribute("target");

const input = document.querySelector("input");
input.value = "Default text";     // form values are properties
input.disabled = true;

Creating and adding elements

You can build new elements from code:

const list = document.querySelector("#list");

const newItem = document.createElement("li");
newItem.textContent = "Three";
newItem.classList.add("item");

list.append(newItem);                 // add to the end
list.prepend(document.createElement("li")); // add to the start

newItem.remove();                     // remove it again

Steps: create the element, set its text and classes, then attach it to something that is already on the page. Until you attach it, the element exists only in memory.

Here is a complete example that builds a list from an array:

const fruits = ["Mango", "Apple", "Banana"];
const ul = document.querySelector("#list");
ul.innerHTML = "";                       // clear the old items

for (const fruit of fruits) {
  const li = document.createElement("li");
  li.textContent = fruit;
  ul.append(li);
}

Notice that we used createElement and textContent, not string-building with innerHTML. It is safer and, with practice, just as quick to write.

Walking the tree

Elements know their neighbours:

const first = document.querySelector(".item");
console.log(first.parentElement.id);       // "list"
console.log(first.nextElementSibling.textContent); // "Two"
console.log(document.querySelector("#list").children.length);

You rarely need this when you can select directly, but it comes in handy inside event handlers.

Common mistakes

  • Script in the head without defer. Elements are not there yet, and querySelector returns null. Put the script at the end of body or add defer to the tag.
  • Reading a property of null. Cannot read properties of null means your selector matched nothing. Check the spelling and the # or . prefix.
  • **Using innerHTML with user input.** Use textContent.
  • Treating querySelectorAll like one element. It gives a list. Loop over it.
  • Forgetting to attach a new element. createElement alone does not show anything.

Try it yourself

  1. Open the console on any web page, select the first h1 or h2 and change its text.
  2. Select every a link on a page and print their href values.
  3. Write code that adds a new li with your name to the list in the starter page.
  4. Use classList.toggle to add and remove a class called dark on the body element.
javascript
const list = document.querySelector("#list");

const newItem = document.createElement("li");
newItem.textContent = "Three";
newItem.classList.add("item");

list.append(newItem);                 // add to the end
list.prepend(document.createElement("li")); // add to the start

newItem.remove();                     // remove it again

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account