elementreplacer.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module utils/elementreplacer
  7. */
  8. /**
  9. * Utility class allowing to hide existing HTML elements or replace them with given ones in a way that doesn't remove
  10. * the original elements from the DOM.
  11. */
  12. export default class ElementReplacer {
  13. constructor() {
  14. /**
  15. * The elements replaced by {@link #replace} and their replacements.
  16. *
  17. * @private
  18. * @member {Array.<Object>}
  19. */
  20. this._replacedElements = [];
  21. }
  22. /**
  23. * Hides the `element` and, if specified, inserts the the given element next to it.
  24. *
  25. * The effect of this method can be reverted by {@link #restore}.
  26. *
  27. * @param {HTMLElement} element The element to replace.
  28. * @param {HTMLElement} [newElement] The replacement element. If not passed, then the `element` will just be hidden.
  29. */
  30. replace( element, newElement ) {
  31. this._replacedElements.push( { element, newElement } );
  32. element.style.display = 'none';
  33. if ( newElement ) {
  34. element.parentNode.insertBefore( newElement, element.nextSibling );
  35. }
  36. }
  37. /**
  38. * Restores what {@link #replace} did.
  39. */
  40. restore() {
  41. this._replacedElements.forEach( ( { element, newElement } ) => {
  42. element.style.display = '';
  43. if ( newElement ) {
  44. newElement.remove();
  45. }
  46. } );
  47. this._replacedElements = [];
  48. }
  49. }