Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. /**
  2. * Simple HTMLElement or HTMLCollection wrapper written in VanillaJS.
  3. * Easy to use:
  4. * 1. Wrap your object. You could send to wrapper one object, collection or just CSS selector.
  5. * Example:
  6. * $(element);
  7. *
  8. * 2. You are available to use these methods, using is similar to JQuery:
  9. * - .map(callback)
  10. * - .forEach(callback)
  11. * - .add(className)
  12. * - .remove(className)
  13. * - .toggle(className)
  14. * - .on(event, handler)
  15. *
  16. * 3. These methods are ordinary aliases for long and boring VanillaJS expressions
  17. * Example:
  18. * document.getElementById("element") => $("element")
  19. * element.classList.add(className) => element.add("className")
  20. * element.addEventListener("click", handler) => element.on("click", handler)
  21. **/
  22. const $ = function(target) {
  23.  
  24. if (typeof target === "string") {
  25. target = document.querySelectorAll(target);
  26. }
  27.  
  28. if (target instanceof HTMLElement) {
  29. target = [target];
  30. }
  31.  
  32. return {
  33.  
  34. target,
  35.  
  36. forEach(callback) {
  37. [].forEach.call(target, callback)
  38. },
  39.  
  40. map(callback) {
  41. return [].map.call(target, callback);
  42. },
  43.  
  44. add(className) {
  45. this.forEach(item => item.classList.add(className))
  46. },
  47.  
  48. remove(className) {
  49. this.forEach(item => item.classList.remove(className))
  50. },
  51.  
  52. toggle(className) {
  53. this.forEach(item => item.classList.toggle(className))
  54. },
  55.  
  56. on(event, handler) {
  57. this.forEach(item => item.addEventListener(event, handler.bind(item)));
  58. }
  59.  
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement