| Conditions | 10 |
| Paths | 24 |
| Total Lines | 38 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 1 | Features | 0 |
Complex classes like dom.js ➔ getClosest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | /*global document */ |
||
| 27 | export function getClosest(elem, selector) { |
||
| 28 | |||
| 29 | var firstChar = selector.charAt(0) |
||
| 30 | |||
| 31 | // Get closest match |
||
| 32 | for ( ; elem && elem !== document; elem = elem.parentNode ) { |
||
| 33 | |||
| 34 | // If selector is a class |
||
| 35 | if ( firstChar === '.' ) { |
||
| 36 | if ( elem.classList.contains( selector.substr(1) ) ) { |
||
| 37 | return elem |
||
| 38 | } |
||
| 39 | } |
||
| 40 | |||
| 41 | // If selector is an ID |
||
| 42 | if ( firstChar === '#' ) { |
||
| 43 | if ( elem.id === selector.substr(1) ) { |
||
| 44 | return elem |
||
| 45 | } |
||
| 46 | } |
||
| 47 | |||
| 48 | // If selector is a data attribute |
||
| 49 | if ( firstChar === '[' ) { |
||
| 50 | if ( elem.hasAttribute( selector.substr(1, selector.length - 2) ) ) { |
||
| 51 | return elem |
||
| 52 | } |
||
| 53 | } |
||
| 54 | |||
| 55 | // If selector is a tag |
||
| 56 | if ( elem.tagName.toLowerCase() === selector ) { |
||
| 57 | return elem |
||
| 58 | } |
||
| 59 | |||
| 60 | } |
||
| 61 | |||
| 62 | return false |
||
| 63 | |||
| 64 | } |