0

I am trying to create a toggle action but with raw JS. So instead of using toggle class I must add and remove each part.

When the user clicks a radio button, one div gets class enabled and the other gets class disabled which controls my styling (to grey the area out)

JS Fiddle showing the problem.

I am using the following for this:

var d = document.getElementById('justfull');
d.className = d.className + " enabled";

and then giving the other div disabled

var other = document.getElementById('firstandlast');
other.className = other.className + " disabled";

But I am stuck when it comes to removing the class if it's previously been added. As obviously the user can toggle between the two radio buttons. I need to add the enabled class to my new div but I also need to check to see if there was previously a disabled class added to it and if so, remove it.

So I am using the following code:

var oldclass="disabled"; 
d.className=d.className.replace(oldclass,"");

But this doesn't seem to work as the classname just adds and adds until I have something like this:

<div id="justfull" class="  enabled  enabled  enabled disabled">

How would I properly both add the enabled class and check for a removal of the other? Essentially a toggle class but in raw JS.

Francesca
  • 26,842
  • 28
  • 90
  • 153
  • You can toggle classes with `Element.classList` - https://developer.mozilla.org/en-US/docs/Web/API/Element.classList - if you're worried about browser compatibility, it can easily be polyfilled – Ian Sep 29 '14 at 14:25
  • Why not actually use the `disabled` attribute of the checkbox input? Then, you can style the spans like: `input + span {}` and `input[disabled] + span {}` – LcSalazar Sep 29 '14 at 14:28
  • Instead of checking or replacing `disabled` class, why don't you just set the class name to `enabled` or `disabled` like `d.className = "enabled";` or `other.className = "disabled";`? – ekad Sep 29 '14 at 14:38
  • the order of the operations might be wrong, but you will get the point... http://jsfiddle.net/sq6r4xc8/ – Sten Muchow Sep 29 '14 at 14:56

0 Answers0