Created
December 22, 2018 15:21
-
-
Save sealucky7/472366eda7631d76a0af5a05a2486e43 to your computer and use it in GitHub Desktop.
Add class in String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Создайте функцию 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