summaryrefslogtreecommitdiffstats
path: root/src/modules/optional/class.js
blob: 3141644891cd85c9c2f1d7a393af7f39b3ed3237 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { delimiter } from '../core/regex.js'
import { registerMethods } from '../../utils/methods.js'

// Return array of classes on the node
export function classes() {
  const attr = this.attr('class')
  return attr == null ? [] : attr.trim().split(delimiter)
}

// Return true if class exists on the node, false otherwise
export function hasClass(name) {
  return this.classes().indexOf(name) !== -1
}

// Add class to the node
export function addClass(name) {
  if (!this.hasClass(name)) {
    const array = this.classes()
    array.push(name)
    this.attr('class', array.join(' '))
  }

  return this
}

// Remove class from the node
export function removeClass(name) {
  if (this.hasClass(name)) {
    this.attr(
      'class',
      this.classes()
        .filter(function (c) {
          return c !== name
        })
        .join(' ')
    )
  }

  return this
}

// Toggle the presence of a class on the node
export function toggleClass(name) {
  return this.hasClass(name) ? this.removeClass(name) : this.addClass(name)
}

registerMethods('Dom', {
  classes,
  hasClass,
  addClass,
  removeClass,
  toggleClass
})