All files / roosterjs-content-model-dom/lib/domUtils moveChildNodes.ts

100% Statements 12/12
100% Branches 8/8
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38            1x 450x 4x     446x 69x     446x 473x                   1x       98x   98x 98x   98x    
/**
 * Replace all child nodes of the given target node to the child nodes of source node.
 * @param target Target node, all child nodes of this node will be removed if keepExistingChildren is not set to true
 * @param source (Optional) source node, all child nodes of this node will be move to target node
 * @param keepExistingChildren (Optional) When set to true, all existing child nodes of target will be kept
 */
export function moveChildNodes(target: Node, source?: Node, keepExistingChildren?: boolean) {
    if (!target) {
        return;
    }
 
    while (!keepExistingChildren && target.firstChild) {
        target.removeChild(target.firstChild);
    }
 
    while (source?.firstChild) {
        target.appendChild(source.firstChild);
    }
}
 
/**
 * Wrap all child nodes of the given parent element using a new element with the given tag name
 * @param parent The parent element
 * @param tagName The tag name of new wrapper
 * @returns New wrapper element
 */
export function wrapAllChildNodes<T extends keyof HTMLElementTagNameMap>(
    parent: HTMLElement,
    tagName: T
): HTMLElementTagNameMap[T] {
    const newElement = parent.ownerDocument.createElement(tagName);
 
    moveChildNodes(newElement, parent);
    parent.appendChild(newElement);
 
    return newElement;
}