Last active
June 29, 2017 09:29
-
-
Save clintonbeattie/8bf1b27c688a71848f14489d8e9e30ae to your computer and use it in GitHub Desktop.
Toggle Class on elements with class name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// document.getElementsByClassName returns an array-like list (an HTMLCollection, to be exact) of all elements that match | |
// the class name. You probably care about the first element, so try using the following instead: | |
var myButton = document.getElementsByClassName( 'myButton' )[0]); | |
// If you care about all of the elements, you'll need to loop through the elements: | |
var myButtons = document.getElementsByClassName( 'myButton' ); | |
for ( var i = 0; i < myButtons.length; ++i ) { | |
myButtons[i].addEventListener('click', function() { | |
// Using an if statement to check the class | |
if (this.classList.contains('open')) { | |
// The box that we clicked has a class of bad so let's remove it and add the good class | |
this.classList.remove('open'); | |
} else { | |
// The user obviously can't follow instructions so let's alert them of what is supposed to happen next | |
this.classList.add('open'); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment