Toggle element's class by ID
11,074
$('#arrow').toggleClass('arrowup arrowdown');
Author by
Jeremy
Updated on June 04, 2022Comments
-
Jeremy almost 2 years
I’m trying to change the class of an element when it is clicked on from one value A to value B and then from value B back to value A when it is clicked a second time. I found some code on here that allowed me to change it once, but not a second time. (See original here).
Here is the original code:
<script type="text/javascript"> function changeClass() { document.getElementById("MyElement").className += " MyClass"; document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/g, '') } </script>
And here is my code:
<script type="text/javascript"> function changeClass() { if (document.getElementByID("arrow").className == "arrowdown") { document.getElementById("arrow").className.replace(/(?:^|\s)arrowdown(?!\S)/g, 'arrowup') } elseif(document.getElementByID("arrow").className == "arrowup") { document.getElementById("arrow").className.replace(/(?:^|\s)arrowup(?!\S)/g, 'arrowdown') } } </script>
-
Jeremy over 11 years
$('#arrow').toggleClass('arrowdown').toggleClass('arrowup');
ah it works! and its jquery... thank you. -
elclanrs over 11 years
$('#arrow').toogleClass('arrowdown arrowup')
-
Jeremy over 11 years@elclanrs that will not work when repeatedly toggled. it seems to keep the class as 'arrowdown arrowup'
-
Jeremy over 11 years@SperanskyDanil looks like it works on there, but I can't seem to get it to work in that format on my page.