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.

6
  • $invoiceTable.display=block well that is not a comparison. So look at the display property or getComputedStyle Commented Aug 24, 2021 at 17:17
  • you could use == "block" Commented Aug 24, 2021 at 17:18
  • 1
    Also, you're checking the style property so, assuming $invoiceTable is an HTMLElement, $invoiceTable.style.display === 'block'. Commented Aug 24, 2021 at 17:18
  • 2
    This seems like a backwards way to do it. Usually the style comes from the class, not the other way around. Commented Aug 24, 2021 at 17:19
  • The style property of an element only contains its inline styles, not styles inherited from CSS. Use getComputedStyle() to get its actual style. Commented Aug 24, 2021 at 17:20

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

5 Comments

Why do you have the addClass calls in quotes? That won't add the classes.
That is just the pseudo code. Refer my last line.
Why post pseudo-code instead of actual code?
Refer the OP's question, he is interested in knowing if styles can be applied based on condition, moreover he has also not provided complete addClass details, like on what element he want;s to apply the style on.
@Barmar I have updated my answer based on your suggestion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.