-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03-dom-manipulation-library-chaining.html
105 lines (88 loc) · 2.62 KB
/
03-dom-manipulation-library-chaining.html
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Library with Chaining</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>DOM Manipulation Library</h1>
<p>All of the fun here happens in the console. <em>🎉</em></p>
<p>
<button class="btn-blue" id="button-1">Button 1</button>
<button class="btn-blue" id="button-2">Button 2</button>
<button class="btn-blue" id="button-3">Button 3</button>
</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
var $ = (function () {
/**
* The constructor object
* @param {String} selector The selector to use
*/
var Constructor = function (selector) {
this.elems = document.querySelectorAll(selector);
};
/**
* Get an immutable copy of the matching elements
* @return {Array} The elements
*/
Constructor.prototype.items = function () {
return Array.prototype.slice.call(this.elems);
};
/**
* Get the first item in a set of elements
* @return {*} The first item
*/
Constructor.prototype.first = function () {
return this.elems[0];
};
/**
* Get the last item in a set of elements
* @return {*} The last item
*/
Constructor.prototype.last = function () {
return this.elems[this.elems.length - 1];
};
/**
* Add a class to every item in a set of elements
* @param {String} className The class to add
*/
Constructor.prototype.addClass = function (className) {
this.items().forEach(function (elem) {
elem.classList.add(className);
});
return this;
};
/**
* Remove a class to every item in a set of elements
* @param {String} className The class to remove
*/
Constructor.prototype.removeClass = function (className) {
this.items().forEach(function (elem) {
elem.classList.remove(className);
});
return this;
};
Constructor.prototype.help = function() {
for (var key in this) {
console.log("%c" + key + "\n\n", "font-size: 1.5em;", this[key]);
}
};
// Return the constructor object
return Constructor;
})();
// Create new instances
var btns = new $('button');
var list = new $('ul');
// Add and remove classes
new $('button').removeClass('btn-blue').addClass('btn-darkmag');
// Helper - 🎩 Kieran Barker
// Display in console with 'new $().help();''
// console.log('$.help()', list.items());
</script>
</body>
</html>