Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Simple HTMLElement or HTMLCollection wrapper written in VanillaJS.
- * Easy to use:
- * 1. Wrap your object. You could send to wrapper one object, collection or just CSS selector.
- * Example:
- * $(element);
- *
- * 2. You are available to use these methods, using is similar to JQuery:
- * - .map(callback)
- * - .forEach(callback)
- * - .add(className)
- * - .remove(className)
- * - .toggle(className)
- * - .on(event, handler)
- *
- * 3. These methods are ordinary aliases for long and boring VanillaJS expressions
- * Example:
- * document.getElementById("element") => $("element")
- * element.classList.add(className) => element.add("className")
- * element.addEventListener("click", handler) => element.on("click", handler)
- **/
- const $ = function(target) {
- if (typeof target === "string") {
- target = document.querySelectorAll(target);
- }
- if (target instanceof HTMLElement) {
- target = [target];
- }
- return {
- target,
- forEach(callback) {
- [].forEach.call(target, callback)
- },
- map(callback) {
- return [].map.call(target, callback);
- },
- add(className) {
- this.forEach(item => item.classList.add(className))
- },
- remove(className) {
- this.forEach(item => item.classList.remove(className))
- },
- toggle(className) {
- this.forEach(item => item.classList.toggle(className))
- },
- on(event, handler) {
- this.forEach(item => item.addEventListener(event, handler.bind(item)));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement