8
0

elementreplacer.js 1.4 KB

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