I have 3 different functions that set a specific style attribute to an element, invoked by clicking 3 different buttons, for example:
element.setAttribute("style","fill:#00ffff");
element.setAttribute("style","fill:#ff00ff");
element.setAttribute("style","fill:#ffff00");
THEN, I have another function invoked by a forth button that updates the style of the same element.
element.setAttribute("style", "transform:translate(29.5%,0px)";
The problem is that when it updates it, the previous attributes, set by the first 3 functions, are removed, so button no#4 translate the element, but the element loses it's fill.
Since the colors are not fixed, I can't solve it by
element.setAttribute("style", "transform:translate(29.5%,0px);fill:#ffff00";
I was hoping for a way that ADDS the attribute rather than update it. I hope I got everything clear for you guys, any ideas?
No libraries allowed for this problem
I have 3 different functions that set a specific style attribute to an element, invoked by clicking 3 different buttons, for example:
element.setAttribute("style","fill:#00ffff");
element.setAttribute("style","fill:#ff00ff");
element.setAttribute("style","fill:#ffff00");
THEN, I have another function invoked by a forth button that updates the style of the same element.
element.setAttribute("style", "transform:translate(29.5%,0px)";
The problem is that when it updates it, the previous attributes, set by the first 3 functions, are removed, so button no#4 translate the element, but the element loses it's fill.
Since the colors are not fixed, I can't solve it by
element.setAttribute("style", "transform:translate(29.5%,0px);fill:#ffff00";
I was hoping for a way that ADDS the attribute rather than update it. I hope I got everything clear for you guys, any ideas?
No libraries allowed for this problem
Share Improve this question edited Jun 17, 2019 at 13:20 IanWing asked Jun 15, 2019 at 18:34 IanWingIanWing 1131 silver badge10 bronze badges 2-
Not saying this is your issue, but your values aren't wrapped with end-quotes, but it's better to go through the
style
property rather than thestyle
attribute of the element – vol7ron Commented Jun 15, 2019 at 18:48 - Yes, sorry, it was just an example that I wrote very quickly. Edited. – IanWing Commented Jun 17, 2019 at 13:21
2 Answers
Reset to default 16from https://www.w3schools./jsref/met_element_setattribute.asp :
Bad
element.setAttribute("style", "background-color: red;");
Good
element.style.backgroundColor = "red";
By choosing the second way, you only overwrite the thing you need
You can use them in this way:-
element.setAttribute("style","fill:#00ffff;")
element.setAttribute("style","fill:#ff00ff;")
element.setAttribute("style","fill:#ffff00;")
element.setAttribute('style', `${element.getAttribute("style")} color:red;`)