10 examples of 'vanilla js add class' in JavaScript

Every line of 'vanilla js add class' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
19function addJsClass(el) {
20 var classes = document.body.className.split(" ");
21 classes.push("js");
22 document.body.className = classes.join(" ");
23}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

19function add(el, className) {
20 if (el.classList) {
21 el.classList.add(className);
22 return;
23 }
24 var current = el.className;
25 if (!current.length) {
26 el.className = className;
27 } else if (!lookupClass(className).test(current)) {
28 el.className += ' ' + className;
29 }
30}
72add: function addClass(el, className) {
73 return el.classList.add(className);
74},
348export function add__class(el, class_name) {
349 return el.classList.add(class_name)
350}
75export function addClass(element, classname) {
76 const classList = element.classList;
77 if (classList) {
78 classList.add(classname);
79 }
80 else {
81 const cls = className(element).split(' '),
82 map = {};
83 each(cls, (klass) => {
84 map[klass] = true;
85 });
86
87 if (!map[classname]) {
88 className(element, cls.join(' ') + classname);
89 }
90 }
91}
18function addClass(className) {
19 this.classList.add(className);
20
21 return this;
22}
105export function add_class(o, cn) {
106 if (!has_class(o, cn))
107 o.className += " " + cn;
108}
3function addOrRemoveClass(el, className, add) {
4 el.classList[add ? 'add' : 'remove'](className);
5}
127var addClass = function addClass(name) {
128 element.classList.add(name);
129};
23public add(...classNames: string[]): void {
24 const attr = this.ownerElement.getAttribute('class');
25 const list = attr ? attr.split(' ') : [];
26 for (const className of classNames) {
27 if (!list.includes(className)) {
28 list.push(className);
29 }
30 }
31 this.ownerElement.setAttribute('class', list.join(' '));
32}

Related snippets