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. return /** @type {!HTMLButtonElement} */(document.createElement('button'));
  33. }
  34. /**
  35. * Cast a Node/Element to an HTMLElement
  36. *
  37. * @param {!Node|!Element} original
  38. * @return {!HTMLElement}
  39. */
  40. static asHTMLElement(original) {
  41. return /** @type {!HTMLElement}*/ (original);
  42. }
  43. /**
  44. * Cast a Node/Element to an HTMLMediaElement
  45. *
  46. * @param {!Node|!Element} original
  47. * @return {!HTMLMediaElement}
  48. */
  49. static asHTMLMediaElement(original) {
  50. return /** @type {!HTMLMediaElement}*/ (original);
  51. }
  52. /**
  53. * Returns the element with a given class name.
  54. * Assumes the class name to be unique for a given parent.
  55. *
  56. * @param {string} className
  57. * @param {!HTMLElement} parent
  58. * @return {!HTMLElement}
  59. */
  60. static getElementByClassName(className, parent) {
  61. const elements = parent.getElementsByClassName(className);
  62. goog.asserts.assert(elements.length == 1,
  63. 'Should only be one element with class name ' + className);
  64. return shaka.util.Dom.asHTMLElement(elements[0]);
  65. }
  66. /**
  67. * Remove all of the child nodes of an element.
  68. * @param {!Element} element
  69. * @export
  70. */
  71. static removeAllChildren(element) {
  72. while (element.firstChild) {
  73. element.removeChild(element.firstChild);
  74. }
  75. }
  76. };