Thursday, 19 May 2016

css - How can I change the class of a button with javascript?




I have this code:



var image = button.getElementsByTagName("span")[0];
if (isEnabled) {
image.style.color = "#BBB"
else {
image.style.color = "#AAA"



Can someone give me some advice on how instead of directly setting a color that I could set the button to have a 3rd class of enabled and then later set it to have a 3rd class of disabled?



Note that my button currently has classes like this:



class="fa fa-bold"
class="fa fa-arrow"


etc.




So I would need the first two classes to be unchanged. Then I need to be able to set to like this:



class="fa fa-bold enabled"
class="fa fa-bold disabled"
class="fa fa-bold enabled"


etc.


Answer




Use classList



To add new class myClass to image, use add():




Adds a class to an element's list of classes. If class already exists in the element's list of classes, it will not add the class again.




image.classList.add('myClass')



To remove class, use remove()




Removes a class from an element's list of classes in a safe manner. Errors are not thrown If the class does not exist.




image.classList.remove('myClass')



To toggle class, use toggle()




If the name exists within the element's classList, it will be removed. If name does not exist, it will be added.




image.classList.toggle('myClass') // If exists, remove, if not add


To check if element has class, use contains()





Checks if an element's list of classes contains a specific class .




if (image.classList.contains('myClass')) {
alert('HasClass myClass');
} else {
alert('Dont have class');
}



CSS



.myClass {
color: #bbb;
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...