Change the `display: none` of elements back to their original value

Explanation

In my coding practice, I have implemented a script that hides certain elements if the user lacks the necessary permission to interact with them. To achieve this, I utilize the CSS property display: none.

However, when it comes time to reveal these hidden elements, I face the dilemma of restoring their display value without assuming it was originally set to block. Is there a method to reset the display property or assign it a generic value?

Example

For instance, consider the element

<div class="fancy-class">...</div>
. If the class fancy-class is styled as inline-block, changing it abruptly to block within my script could disrupt the user interface.

Efforts

I have experimented with utilizing display: initial; however, this action merely reverts the styling to the default settings specified for HTML elements rather than capturing the original class-specific styles. Resorting to storing and reapplying the original values in an array seems cumbersome and inelegant.

Answer №1

For resetting the style.display of an element, you can use the following code: element.style.display = ""

(() => {
  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>

Answer №2

Prior to hiding an element by setting its display to none, it's helpful to save the current display value and reapply it later.

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

Restore the original display attribute using the previously saved value.

document.getElementById("fancy-class").style.display = savedDisplay;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

$scope.apply is triggering both "catch" and "then" handlers

I am trying to ensure that the content of a page in Angular 1.6.2 and UI router is only displayed once it has been confirmed on the server that the user has the appropriate role/permissions. It seems like without using $scope.apply(), the catch() function ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...

Error: The Typescript module in Angular 2 does not have the constant 'FORM_DIRECTIVES' available for export

I need to integrate an existing component into my app, but I am facing some issues with the dependencies. Originally, the sample code provided me with these dependencies: import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from 'angular2/common'; ...

Enable the ability for anchor links to be clickable when the CSS media print format is used to generate

To illustrate: <a href="https://www.google.com">Google anchor link</a> on the website, it displays as: Google anchor link When printed, it shows as: Google anchor link(https://www.google.com) To address this issue, I included in the CSS: ...

Guide on converting a date input to a timestamp

I am trying to convert the date retrieved from an HTML5 date input into a timestamp and store it as a variable. HTML: <form> <section class="input"> <input type="date" id="date" name="maintenanace_date"/> </section> <sectio ...

send the ID of the element as an argument in jQuery

A web form I am working on contains a select box that, when a specific option is chosen, reveals a hidden div. <script> $(document).ready(function () { $("#Select1").change(function () { $(this).find("option:selected").each(function(){ ...

Tips for Aligning Form Elements in the Middle using Bootstrap

What could be the issue? I can clearly see the container border, indicating the space available for my work. However, when I insert the row (div) and offset (div), the content gets left-justified. <div id="page" class="container" style="border:soli ...

Google Chrome extension with Autofocus functionality

I developed a user-friendly Chrome extension that allows users to search using a simple form. Upon opening the extension, I noticed that there is no default focus on the form, requiring an additional click from the user. The intended behavior is for the ...

The Vuetify v-img component fails to display images when using absolute paths

Having a bit of trouble here: I want to showcase an image using an absolute path in Vuetify with the v-img tag, but for some reason, it's not displaying. I attempted to use :src="require('path/to/img')", but it throws an error saying "This ...

Tips for keeping a login session active on multiple tabs

As I am in the process of developing a website, one issue I am facing is determining the most effective method to maintain user login sessions. Currently, I am utilizing Html5 web storage known as "session storage" to keep track of whether a user is logged ...

Searching by multiple parameters in Angular.js

I have a script that scans through a field and highlights the words related to the search input. I want this script to not only filter by title, but also by name. How can I adjust the code to filter both the title and name when searching? <li ng-repeat ...

The jsx file is not being parsed by Webpack

In my current project, I am working with a JSX file that contains React code. import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { render () { return <p> Hello React!</p>; ...

What is the best way to showcase two data frames side by side in an HTML template or webpage without using frames?

Is there a way to showcase two data frames side by side in an html template? <h3> TITLE </h3> {{stat1 | safe}}. {{stat | safe}} I attempted the above solution, but unfortunately it only displays the data frames vertically stacked instead of ...

Utilizing variables across various scopes in AngularJS

I am working on an AngularJS controller where I have defined a 'MapCtrl' function. In this function, I am trying to retrieve the user's current position using geolocation and store it in a variable called curPos. However, when I try to log t ...

What causes HttpPostedFileBase to fail on large files before reaching server-side validation?

When I disable client side validation <add key="ClientValidationEnabled" value="false" /> <add key="UnobtrusiveJavaScriptEnabled" value="false" /> and attempt to upload a file that is approximately 11 MB, which is then assigned to a HttpPost ...

The fontloader in three.js encountered an error while trying to read undefined generateshapes

I'm encountering an issue with my code where I am trying to generate meshes and add 3D text to a scene. However, whenever I attempt to do this, I receive the following error message: TypeError: Cannot read property 'generateShapes' of und ...

Tips for combining all included files into one with Babel

My current project involves the use of Babel. Within my server.js file, I have the following line of code: import schema from "./data/schema"; The issue arises because data/schema.js is written in ES2015 syntax. After attempting to compile my server.js ...

Unable to retrieve DateTime.Now as a string within a Razor view

I am trying to retrieve the current time in a Razor View and utilize it in JavaScript, as demonstrated below: @{ string fileName = "Score_List_" + DateTime.Now.ToShortDateString(); } <script> // assigning C# variable to JavaScript variabl ...

give parameters to a node function being exported

Script.js var routes = require('../controllers/routes.server.controller'); module.exports = function(app) { app.get('/',function(request,response){ return response.send("Welcome to the website"); }); app.route(' ...

div value causing erratic behavior in cycling process

Instead of following the normal balance calculation (1000-950), something odd happens and the balance goes from 1000 to 0 with the while loop. I never intended for the refBalance to drop below 0. (numDebit2() returns 50) <div class="elemen ...