0

Is it possible to conditionally add a class to an element based on its display property (eg. display: block, display: none) in JavaScript?

I'm guessing it would look something like this:

.addClass($invoiceTable.display=block ? "firstClass" : "secondClass");

where firstClass is added if invoiceTable has style="display: block", else the secondClass is added.

epascarello
  • 204,599
  • 20
  • 195
  • 236

1 Answers1

0

One way to achieve this would be to store the style attribute of that element to a variable and check if is display or block and based on that you can add class.

Something like this:

const display =  document.getElementById("invoiceTable").style.display; // Inline style

or, if the display property is an inherited property:

  const display =   window.getComputedStyle(document.getElementById("invoiceTable"), null).display;

and then add your classes based on display:

display === 'block' ? element.classList.add("block") : element.classList.add("other");
Ritesh Waghela
  • 3,474
  • 2
  • 19
  • 25