skip to Main Content

In some JavaScript, I hide an element by doing this:

element.style.display = 'none';

When I want to display it again, I could do that same thing and set it to block. However, I won’t know what it was before I changed it. It could have been inline-block for all I know.

This means that I can’t really use this method, unless I wanted to store the prior value first. (Something I could conceivably do…)

I thought about moving to some hidden area (like a template tag or something), but then I’d have to have some way of remembering exactly where it came from.

Is there another way to remove an element from the layout (so display, not visibility), without changing the display style property, so that I don’t have to worry about getting it back to what it was?

2

Answers


  1. You can store the state it was before setting it to none.

    function hide(element) {
      element.setAttribute("data-old-display", element.style.display);
      element.style.display = 'none';
    }
    
    function restore(element) {
      element.style.display = element.getAttribute("data-old-display");
    }
    .square {
      width: 50px;
      height: 50px;
      display: inline-block;
      background: red;
    }
    <button onclick="hide(document.querySelector('.square'))">hide</button>
    <button onclick="restore(document.querySelector('.square'))">restore</button>
    <div class="square">
    </div>
    Login or Signup to reply.
  2. Set an empty string to the display property

    function hide() { 
      document.querySelector(".box").style.display="none"
    }
    function show() { 
      document.querySelector(".box").style.display=""
    }
    .box {
      width: 200px;
      aspect-ratio: 1;
      display: inline grid;
      place-content: center;
      border: 1px solid red;
    }
    
    button {
      font-size: 25px;
    }
    <button onclick="hide()">hide</button>
    <button onclick="show()">show</button>
    <br>
    <div class="box">text</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search