attributes.js

  1. /**
  2. * Id, class and attribute related functions
  3. *
  4. * @namespace Attributes
  5. */
  6. /**
  7. * Add one or more classes to an element
  8. * @memberof Attributes
  9. * @param { Element } el
  10. * @param { ...String } className
  11. */
  12. function addClass(el, ...className) {
  13. el.classList.add(...className);
  14. }
  15. /**
  16. * Check if an element has a given class
  17. * @memberof Attributes
  18. * @param { Element } el
  19. * @param { String } className
  20. * @return { Bool }
  21. */
  22. function hasClass(el, className) {
  23. return el.classList.contains(className);
  24. }
  25. /**
  26. * Remove a class from an element
  27. * @memberof Attributes
  28. * @param { Element } el
  29. * @param { String } className
  30. */
  31. function removeClass(el, className) {
  32. el.classList.remove(className);
  33. }
  34. /**
  35. * Toggle a class on an element
  36. * @memberof Attributes
  37. * @param { Element } el
  38. * @param { String } className
  39. */
  40. function toggleClass(el, className) {
  41. if (hasClass(el, className)) removeClass(el, className);
  42. else addClass(el, className);
  43. }
  44. /**
  45. * Check if an element has a given attribute
  46. * @memberof Attributes
  47. * @param { Element } el
  48. * @param { String } attr
  49. * @return { Bool }
  50. */
  51. function hasAttribute(el, attr) {
  52. return el.hasAttribute(attr);
  53. }
  54. /**
  55. * Get an attribute's value from an element
  56. * @memberof Attributes
  57. * @param { Element } el
  58. * @param { String } attr The attribute's name
  59. * @return { String }
  60. */
  61. function getAttribute(el, attr) {
  62. return el.getAttribute(attr);
  63. }
  64. /**
  65. * Add or set an attribute on an element
  66. * @memberof Attributes
  67. * @param { Element } el
  68. * @param { String } attr The attribute's name
  69. * @param { String } val The attribute's value
  70. */
  71. function setAttribute(el, attr, val) {
  72. el.setAttribute(attr, val);
  73. }
  74. /**
  75. * Remove an attribute from an element
  76. * @memberof Attributes
  77. * @param { Element } el
  78. * @param { String } attr The attribute's name
  79. */
  80. function removeAttribute(el, attr) {
  81. el.removeAttribute(attr);
  82. }
  83. export {
  84. addClass,
  85. hasClass,
  86. removeClass,
  87. toggleClass,
  88. hasAttribute,
  89. getAttribute,
  90. setAttribute,
  91. removeAttribute
  92. };