How do I change the overall styling of the card using javascript?

I’m basically trying to change the .card styling dynamically depending on the fields on the card. I thought the best way to do it would be to leave .card itself blank and then add the style I want conditionally.

There seems to be only one element with class “card”. I tried:

document.getElementsByClassName(“card”)[0].classList.add(“card_t”);

but the styling didn’t change.

I then tried:

document.getElementsByClassName(“card”)[0].classList.add(“card_t”);
document.getElementsByClassName(“card”)[0].classList.remove(“card”);

in case the blank .card styling was somehow overriding the card_t styling. Nothing happens though.

If I put e.g. document.getElementsByClassName(“card”)[0].style = “background-color: white”, that works just fine. There are a lot of styling attributes (attributes?) though so it seems neater to define them as a class style and apply them as a set.

Can someone let me know what I’m doing wrong? Maybe the card class is some sort of special class you can’t tamper with, idk.

If you trying to change css class you need to operate on said class and not on elements with that class ( what you are doing in your examples).

As you initially thought, I think it would be much easier to just have bunch of css classes and toggle/add/remove them as needed on elements with fields of your choice (doing same thing in my deck). No idea if ‘card’ class is somehow special, but without some example deck there is too much things you could do wrong.

For example this is how I hide/show some element with text:

// toggle hidden text
document.querySelectorAll("div.hidden-text > div").forEach(element => element.addEventListener("click", function (e) {
    this.classList.toggle("showed");
}));

What i’m doing in example is toggling class “showed” on click on div inside div with class “hidden-text”. Click to show, another click to hide again.

But if you really want to fiddle with one class then you will need operate on them (CSSStyleSheet) inside document.styleSheets object.

4 Likes

Thanks. In the end I restyled it so that the difference between the styles was only that one had a background image and the other one didn’t. I just manually remove / put back the background image that’s specified in the .card style.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.