1

I have an html element that has a set style.

element.style {
  "existing css;"
}

I want to add on to the style without overwriting the "existing css". (e.g my style is opacity and pointer-events)

element.style = "opacity: 0; pointer-events: none;"

Result I'm looking for:

element.style {
  existing css;
  opacity: 0;
  pointer-events: none;
}

Current Output:

element.style {
  opacity: 0;
  pointer-events: none;
}    

I know I can just add a class but want to know if theres a way to use javascripts element.style = "css". I have also tried:

element.style += "opacity: 0; pointer-events: none;

Any feedback will be greatly appreciated.

Jonathan002
  • 9,639
  • 8
  • 37
  • 58
  • Let me get this straight. For each of the CSS key/value pairs you're trying to apply to the element, you want to apply them as inline styling, but only if the existing inline styling doesn't already have a set value to the current CSS property. Is that it? Or do you want to overwrite the new value regardless of what's already in the element's inline style? – tao Jun 17 '22 at 21:55

3 Answers3

1

This code:

element.style.setProperty("some_property", "some_value", "important");

will append a the style "some_property" with a value of "some_value" and mark it as "important", i.e. element {some_property: some_value !important;}.

so for your specific case,

element.style.setProperty("opacity", "0");
element.style.setProperty("pointer-events", "none");

should get the job done.

However, I've also ran across some code where you can apparently do something as simple as, element.style["some_property"] = "some_value";, but I don't think you will have the option as marking it as !important. I haven't tried this out myself, yet!

This question is definitively a repeat - see this answer.

Shmack
  • 1,933
  • 2
  • 18
  • 23
0
var d = document.getElementById("div1");
d.className += " otherclass";
user5328504
  • 734
  • 6
  • 21
0
document.getElementById("div1").className += "otherclass";
  • "I know I can just add a class but want to know if theres a way to use javascripts element.style = "css"" – ESR Apr 26 '17 at 05:37