1

Hi I have a problem with my code. I want to set display: block when i click on "start" button. I created addevenlistener on click but something is wrong. Can anyone to help me?

const ulElement = document.querySelectorAll("li");
const btn = document.querySelector("button");


function changeSize() {
  ulElement.style.display = "block";
}

btn.addEventListener("click", changeSize);
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>list</title>
    <style>
      li {
        display: none;
      }
    </style>
  </head>

  <body>
   

    <button>Start</button>
    <ul>
      <li>element 1</li>
      <li>element 2</li>
      <li>element 3</li>
      <li>element 4</li>
      <li>element 5</li>
      <li>element 6</li>
      <li>element 7</li>
      <li>element 8</li>
      <li>element 9</li>
      <li>element 10</li>
    </ul>

    <script src="main.js"></script>
  </body>
</html>
jasper93
  • 69
  • 6
  • 2
    There is an error message in your console. What have you done to fix that? `document.querySelectorAll` returns a NodeList, which does not have a style attribute. – mykaf Dec 30 '22 at 19:59
  • https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return – Konrad Dec 30 '22 at 20:00

2 Answers2

1

You have querySelectorAll you have selected all the liElements and you should have an array node lists not a single element hence why you can't just use e.style.display on an array, what you need to do is loop through all the items and set thier display one by one

const ulElement = document.querySelectorAll("li");
const btn = document.querySelector("button");


function changeSize() {
  ulElement.forEach(e => e.style.display = "block")
  //ulElement.style.display = "block";
}

btn.addEventListener("click", changeSize);
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>list</title>
    <style>
      li {
        display: none;
      }
    </style>
  </head>

  <body>
   

    <button>Start</button>
    <ul>
      <li>element 1</li>
      <li>element 2</li>
      <li>element 3</li>
      <li>element 4</li>
      <li>element 5</li>
      <li>element 6</li>
      <li>element 7</li>
      <li>element 8</li>
      <li>element 9</li>
      <li>element 10</li>
    </ul>

    <script src="main.js"></script>
  </body>
</html>
Sarkar
  • 1,225
  • 7
  • 21
1

Not sure if this is what you had in mind but if you change:

li {
        display: none;
      }

to:

ul {
        display: none;
      }

And if you change:

const ulElement = document.querySelectorAll("li");

to:

const ulElement = document.querySelector("ul");

Then it will work the list will appear after clicking on the button....