Error: Cannot read properties of undefined


I’m trying to add "pop-up" class to my "turnGreen" but turnGreen.classList is undefined.

How can I handle this error?

function turnGreen(cornerNumber) {
  const selectedCorner = "corner-" + cornerNumber;
  const turnGreen = document.getElementsByClassName(selectedCorner);
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <div class="container">
      <div class="corner corner-1"><p>1</p></div>
      <div class="corner corner-2"><p>2</p></div>
      <div class="corner corner-3"><p>3</p></div>
      <div class="corner corner-4"><p>4</p></div>
      <div class="corner corner-5"><p>5</p></div>
      <div class="corner corner-6"><p>6</p></div>
      <button id="start-button" class="control start">Start</button>
      <button id="stop-button" class="control stop">Stop</button>
    <script src="script.js"></script>

>Solution :

The getElementsByClassName returns an iterable collection of elements. So if you want to add a class in it you have to do that:

Pro tip: Do not declare a function and variable with the same name. As it is hard to read and understand.

function turnGreen(cornerNumber) {
  const selectedCorner = "corner-" + cornerNumber;
  const turn_green = document.getElementsByClassName(selectedCorner);

Instead of getting elements by class name, using querySelector() would be preferable. You don’t need to access the first element in the collection because querySelector() returns the first element in the page that matches the given selector.


function turnGreen(cornerNumber) {
  const selectedCorner = ".corner-" + cornerNumber;
  const turn_green = document.querySelector(selectedCorner);

The querySelector() function is now used in place of the getElementsByClassName method, and selectedCorner now begins with a period to signify a class selector.

In general, picking elements with querySelector() is more effective because it enables more precise selections, which decreases the number of elements the browser must look through to find a match.

Leave a Reply Cancel reply