-1

explanation

I have a script that hides elements, if the user does not have the permission to view/use it. I set display: none for those elements.

Now later, when I want to show the elements again, I don't just want to set display: block or something, because maybe the elements original display value was something other than block. Is there a way I can revert the display or set it to a neutral value?

example

E.g. <div class="fancy-class">...</div> If fancy-class has display set to inline-block and I just set it to block with my script, that will break the ui.

attempts

I have tried using display: initial but that resets it to the HTML-element's initial styling - not the class's styling. I hope I don't have to keep the original values in an array and then apply them again. Doesn't seem nice.

Community
  • 1
  • 1
molerat
  • 946
  • 4
  • 15
  • 43
  • 3
    If you want to reset `style.display` to its original value use: `element.style.display = ""` – KooiInc Aug 03 '18 at 08:39
  • 1
    Store it in as a data-attriute to element by getting display property using window.getComputedStyle on page load and then retrieve it and apply when you need it. – jeetaz Aug 03 '18 at 08:39
  • @KooiInc simple as that - it worked just the way I wanted - thanks! – molerat Aug 03 '18 at 08:40
  • @jeetaz also interesting, but I feel like the other option is simpler, thank you though! – molerat Aug 03 '18 at 08:40

2 Answers2

2

use: element.style.display = "" to reset style.display of an element

(() => {
  const displayState = reset => 
    Array.from(document.querySelectorAll("div"))
      .forEach( el => el.style.display = reset ? "" : "none" );
    //                                           ^ restore original display state
  document.querySelector("#showAll").addEventListener("click", () => displayState(true));
  document.querySelector("#hideAll").addEventListener("click", () => displayState());
})();
#first, #second, #third {
  display: inline-block;
  margin-right: 1em;
}
<div id="first">[First]</div>
<div id="second">[Second]</div>
<div id="third">[Third]</div>
<button id="showAll">show divs</button>
<button id="hideAll">hide divs</button>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

Before setting display to none, you can save it, and apply it back.

var display = document.getElementsByClassName("fancy-class").style.display;
document.getElementById("fancy-class").style.display = none;

Set above saved attribute.

document.getElementById("fancy-class").style.display = display;
Dheeraj Kumar
  • 3,917
  • 8
  • 43
  • 80