Source: lib/util/dom_utils.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.Dom');
  7. goog.require('goog.asserts');
  8. // TODO: revisit this when Closure Compiler supports partially-exported classes.
  9. /** @export */
  10. shaka.util.Dom = class {
  11. /**
  12. * Creates an element, and cast the type from Element to HTMLElement.
  13. *
  14. * @param {string} tagName
  15. * @return {!HTMLElement}
  16. */
  17. static createHTMLElement(tagName) {
  18. const element =
  19. /** @type {!HTMLElement} */ (document.createElement(tagName));
  20. return element;
  21. }
  22. /**
  23. * Create a "button" element with the correct type.
  24. *
  25. * The compiler is very picky about the use of the "disabled" property on
  26. * HTMLElement, since it is only defined on certain subclasses of that. This
  27. * method merely creates a button and casts it to the correct type.
  28. *
  29. * @return {!HTMLButtonElement}
  30. */
  31. static createButton() {
  32. const button = document.createElement('button');
  33. button.setAttribute('type', 'button');
  34. return /** @type {!HTMLButtonElement} */ (button);
  35. }
  36. /**
  37. * Cast a Node/Element to an HTMLElement
  38. *
  39. * @param {!Node|!Element} original
  40. * @return {!HTMLElement}
  41. */
  42. static asHTMLElement(original) {
  43. return /** @type {!HTMLElement}*/ (original);
  44. }
  45. /**
  46. * Cast a Node/Element to an HTMLCanvasElement
  47. *
  48. * @param {!Node|!Element} original
  49. * @return {!HTMLCanvasElement}
  50. */
  51. static asHTMLCanvasElement(original) {
  52. return /** @type {!HTMLCanvasElement}*/ (original);
  53. }
  54. /**
  55. * Cast a Node/Element to an HTMLMediaElement
  56. *
  57. * @param {!Node|!Element} original
  58. * @return {!HTMLMediaElement}
  59. */
  60. static asHTMLMediaElement(original) {
  61. return /** @type {!HTMLMediaElement}*/ (original);
  62. }
  63. /**
  64. * Returns the element with a given class name.
  65. * Assumes the class name to be unique for a given parent.
  66. *
  67. * @param {string} className
  68. * @param {!HTMLElement} parent
  69. * @return {!HTMLElement}
  70. */
  71. static getElementByClassName(className, parent) {
  72. const elements = parent.getElementsByClassName(className);
  73. goog.asserts.assert(elements.length == 1,
  74. 'Should only be one element with class name ' + className);
  75. return shaka.util.Dom.asHTMLElement(elements[0]);
  76. }
  77. /**
  78. * Remove all of the child nodes of an element.
  79. * @param {!Element} element
  80. * @export
  81. */
  82. static removeAllChildren(element) {
  83. while (element.firstChild) {
  84. element.removeChild(element.firstChild);
  85. }
  86. }
  87. };