21. DOM Manipulation 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
/* For today’s project, we’re going to build a small DOM manipulation library
(a bit like a small, personal jQuery). */

const $ = (function () {

// Create Constructor function here
const Constructor = function (selector) {
this.elements = document.querySelectorAll(selector);
};

// Immutable copy of the matching elements
Constructor.prototype.items = function () {
return Array.prototype.slice.call(this.elements);
};

// Get first item
Constructor.prototype.first = function () {
return this.elements[0];
}

// Get last item
Constructor.prototype.last = function () {
return this.elements[this.elements.length - 1];
}

// Add class to element
Constructor.prototype.addClass = function (newClass) {
this.items().forEach(element => {
element.classList.add(newClass);
})
};

// Remove class from element
Constructor.prototype.removeClass = function (newClass) {
this.items().forEach(element => {
element.classList.remove(newClass);
})
};

return Constructor;
})();

// Create new instance
const btns = new $('.button')

// Check the console logs in dev tools
console.log('$.items()', btns.items());
console.log('$.first()', btns.first());
console.log('$.last()', btns.last());

// Add and remove class
btns.addClass('btn-purple');
btns.removeClass('btn-blue');