-
-
Save ethertank/2286851 to your computer and use it in GitHub Desktop.
addClass()
This file contains hidden or 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
function addClass(elem, newClassName) { | |
var className, classes, classesLength; | |
if(typeof elem === 'string') { elem = document.getElementById(elem); } | |
if(elem === null || elem.nodeType !== 1 || typeof newClassName !== 'string') { return null; } | |
className = elem.className; | |
classes = newClassName.split(' '), | |
classIndex = classes.length; | |
while(classIndex--) { | |
className = (className.match(new RegExp('\\b'+classes[classIndex]+'\\b')) === null ? className +' '+ classes[classIndex] : className); | |
} | |
elem.className = className; | |
return elem; | |
} |
This file contains hidden or 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
## 関数の中でやってる事 ## | |
1, 引数elemが文字列で有った場合はそのidを持つ要素を対象とする。 | |
2, 引数 elem が | |
・内容を持たない場合、 | |
・nodeType が ELEMENT_NODE 以外の場合、 | |
・文字列でない場合 | |
には何もしない。 | |
3, 引数 newClassName を半角スペースで分割し、配列としてclassesに代入。classIndexにその個数を代入。 | |
classes の配列要素それぞれに対し、既存のクラス名の前後に半角英数字とアンダーバーを伴わない形で検索し(重複対策)、 | |
null の場合はclassName変数に直接代入。 | |
一致した場合、半角スペース付きで追加。 | |
4, 対象要素のクラス名に、加工済みのclassNameを代入 | |
5, 要素をリターン | |
## ポイント ## | |
・厳密な引数チェックと、id文字列による対象要素指定機能の付与による冗長化。 | |
・if(classes === '') {} else {} とはせず、既存クラス名との重複チェックの為の正規表現部分に、兼ねさせている。 | |
・Cool!(・∀・)b | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment