Skip to content

Instantly share code, notes, and snippets.

@mrfoxtalbot
Last active September 14, 2019 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrfoxtalbot/435e4de76927707558514ef9bac0d00b to your computer and use it in GitHub Desktop.
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
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