Skip to content

Instantly share code, notes, and snippets.

@sealucky7
Created December 22, 2018 15:21
Show Gist options
  • Save sealucky7/472366eda7631d76a0af5a05a2486e43 to your computer and use it in GitHub Desktop.
Save sealucky7/472366eda7631d76a0af5a05a2486e43 to your computer and use it in GitHub Desktop.
Add class in String
Создайте функцию addClass(obj, cls), которая добавляет в список класс cls, но только если его там еще нет.
----------------------------------------------------------------------------------------------------------
function addClass(obj, cls){
var allClasses = obj.className;
var arrClasses = allClasses.split(' ');
for(var i = 0; i < arrClasses.length; i++){
if(arrClasses[i] === cls) {
return
}
}
arrClasses.push(cls);
obj.className = arrClasses.join(' ');
}
var obj = {
className: 'open menu'
}
addClass(obj, 'new'); // obj.className='open menu new'
addClass(obj, 'open'); // без изменений (класс уже существует)
addClass(obj, 'me'); // obj.className='open menu new me'
console.log( obj.className ); // "open menu new me"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment