(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/
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?
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.