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
|
const btns = document.querySelectorAll('.button'); const btn2 = document.querySelector('#button-2');
const helperMethod = (function () {
const 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); }) } };
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; })();
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'));
helperMethod.addClass(btns, 'btn-purple'); helperMethod.removeClass(btn2, 'btn-purple');
|