Skip to content

Instantly share code, notes, and snippets.

@DakotaLMartinez
Created December 23, 2020 17:41
Show Gist options
  • Save DakotaLMartinez/5745cdd405f5ab5cb41292ecafbb30a6 to your computer and use it in GitHub Desktop.
Save DakotaLMartinez/5745cdd405f5ab5cb41292ecafbb30a6 to your computer and use it in GitHub Desktop.
How to Set the ClassList of a DOM element using a string

After writing a bunch of code like this:

this.actionButton.classList.add(..."px-4 bg-transparent p-3 rounded-lg text-indigo-500 hover:bg-gray-100 hover:text-indigo-400 mr-2".split(" "));

When building up javascript elements with lots of classes from html, I finally wised up and made a change:

DOMTokenList.prototype.set = function(classString) {
  this.add(...classString.split(" "));
}
// now I can do this:
this.actionButton.classList.set("px-4 bg-transparent p-3 rounded-lg text-indigo-500 hover:bg-gray-100 hover:text-indigo-400 mr-2")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment