Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Change class of an element with JS

Hi,

 

I understood that I can change the style of elements one by one by manipulating the *style property*. This is OK, but I was wondering if there is a way to change classes the same way we can do in modern JS. For example:

 

 

let myBigBox = document.getElementById("myBigBox");
myBox.classList.add("bigBox");
mybox.classList.remove("blue"); let myLittleRedBox = document.getElementById("myLittleBox"); myLittleRedBox.classList.add("littleBox"); myLittleRedBox.classList.add("red");

I tried to use the *classList* property, but I keep getting the classic *undefined*. Let me know if this is possible. Thanks!

 

Best Answer
0 Votes
9 REPLIES 9

Maybe this will work?

myLittleRedBox.className += " littleBox red";
Best Answer
0 Votes

Unfortunately there's no way to dynamically change an element's class name right now.

Best Answer

This might work if your case is very simple. There are a few problems with this implementation:

1) You will concatenate more than one class if your event happens more than once;

2) To remove is a pain; You probably have to use something like

myLittleRedBox.className = myLittleRedBox.replace('your-unique-class', '');
// or use regex, splice, etc...

Thanks for the suggestion, though. I appreciate it.

Best Answer
0 Votes

You can retrieve the separate classes by string manipulation. It's not very "clean" but it's possible.

 

Here are the steps you can take (untested, by the top of my head):

 

 

var classesAsString = myLittleRedBox.className;
// maybe remove all spaces beforehand with eg this replace solution
// put the classNames in an array by splitting on the comma
var classesSplit = classesAsString.split(",");
// remove class by splicing the classname you want to remove
var indexOfClassToRemove = classesSplit .indexOf("classToRemove"); if (index > -1) { classesSplit.splice(index, 1); }
// build up the new class value by using join
myLittleRedBox.className = classesSplit.join();

 

 

Best Answer
0 Votes

Fundamental problem is that neither className or classList are exposed in JS, as JonFitbit already said.

Both give undefined, so nothing is going to work.

This is a real pain - the idea of using SVG for the UI is cool, but not if basic manipulation features are missing.

Best Answer

Not being able to change a className on an element is a huge pain in the arse and a tragic hole in the SDK capabilities.

Best Answer

class is now supported in SDK 4, and it works great - you can easily change  colours and visibility just by changing the class of the SVG element with the appropriate CSS.

 

Nice 🙂

Best Answer
0 Votes

Any update on this. Is this possible yet?

Best Answer
0 Votes
Best Answer