20. Helper Library

HTML

1
2
3
4
5
6
7
8
<p>
<button class="btn-blue button" id="button-1">Button 1</button>
<button class="btn-blue button here-is-johnny" id="button-2">Button 2</button>
<button class="btn-blue button" id="button-3">Button 3</button>
<button class="btn-blue button" id="button-4">Button 4</button>
<button class="btn-blue button" id="button-5">Button 5</button>
<button class="btn-blue button here-is-johnny" id="button-6">Button 6</button>
</p>

JavaScript

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* In today’s project, we’re going to create a helper library. */

const btns = document.querySelectorAll('.button');
const btn2 = document.querySelector('#button-2');

const helperMethod = (function () {

// Hold public methdos here
const methods = {};

// Private methods
const nodeToArr = function (node) {
return Array.prototype.slice.call(node);
};

const getFirstMatch = function (element, match) {
return element.closest(match);
};

const getAllMatches = function (match) {
return nodeToArr(document.querySelectorAll(match));
};

const addClassToElem = function (elements, newClass) {
if (nodeToArr(elements).length == 0) {
return elements.classList.add(newClass);
} else {
return nodeToArr(elements).map(element => {
element.classList.add(newClass);
})
}
};

const removeClassFromElement = function (elements, newClass) {
if (nodeToArr(elements).length == 0) {
return elements.classList.remove(newClass);
} else {
return nodeToArr(elements).map(element => {
element.classList.remove(newClass);
})
}
};

// Public methods
methods.transformToArray = function (node) {
return nodeToArr(node);
};

methods.firstMatch = function (element, match) {
return getFirstMatch(element, match);
};

methods.allMatches = function (match) {
return getAllMatches(match);
};

methods.addClass = function (elements, newClass) {
return addClassToElem(elements, newClass);
};

methods.removeClass = function (elements, newClass) {
return removeClassFromElement(elements, newClass);
}

return methods;
})();

// Check the console logs in dev tools
console.log('helperMethod.transformToArray(btns)', helperMethod.transformToArray(btns));
console.log('helperMethod.firstMatch(btn2, ".here-is-johnny")', helperMethod.firstMatch(btn2, '.here-is-johnny'));
console.log('helperMethod.allMatches(".here-is-johnny")', helperMethod.allMatches('.here-is-johnny'));

// Add and remove classes
helperMethod.addClass(btns, 'btn-purple');
helperMethod.removeClass(btn2, 'btn-purple');