Last active
September 14, 2019 16:48
-
-
Save mrfoxtalbot/435e4de76927707558514ef9bac0d00b to your computer and use it in GitHub Desktop.
JS Add a classname to one or various element using a CSS selector
This file contains 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.querySelector('.foo').classList.add('mystyle') | |
// This will add a classname (.mystyle) to the first element that matches that CSS selector (.foo) | |
document.querySelectorAll('.foo')[2].classList.add('mystyle') | |
// This will add a classname (.mystyle) to the third element that matches that CSS selector. | |
document.querySelectorAll('.foo').forEach(function(i){i.classList.add('mystyle')}) | |
// This will add a classname (.mystyle) to ALL elements that match that CSS selector. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment