Home > Enterprise >  set display: block in javascript doesnt work
set display: block in javascript doesnt work

Time:12-31

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>

CodePudding user response:

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....

CodePudding user response:

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>

  • Related