add/removeClass, simple and fast, No JQuery

(function() { UIUtility = { addClass: function (el, className) { if('string' === typeof className) className = className.split(' '); for(var i = 0, c = ''; i < className.length; i++) { c = className[i]; if (!c) continue; if (el.classList) el.classList.add(c); else el.className += ' ' + c; } return el; }, removeClass: function (el, className) { if (el.classList) el.classList.remove(className); else el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); return el; } }; })();
I use this 2 methods to add or remove class to the DOM elements. They are simple to use and faster than JQuery add/removeClass functionality.

Why is it faster than JQuery?
To use JQuery add/removeClass, you need to convert the DOM element to jq Object -> Cost extra resource.
JQuery also tries to be forgiving so it ignores some programming errors which can results to a low quality code.

See the example at: https://jsfiddle.net/Lfp52pw4/

5 Responses


Hello Eeliya, the snippet look great, can you write line to test this snippet on HTML file with diferents tags?
@Galileo Guzmán Hi, Thank you.But what do you by test, like create an example use case in jsFiddle or something like that?
@Eeliya Yes Eeliya, jsFiddle sounds great. Can you do that?
@Galileo Guzmán Sure, no problem
@Galileo Guzmán I have added the example, plz let me know if you have any other question :)

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.