All files / roosterjs-content-model-plugins/lib/pluginUtils/CreateElement createElement.ts

100% Statements 25/25
95.83% Branches 23/24
100% Functions 4/4
100% Lines 25/25

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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561x                   1x 532x 1x     3717x 531x       531x 468x     531x 217x     531x 167x 331x       531x 39x 111x       531x 239x 310x 13x 297x 296x 296x 296x           531x    
import { getObjectKeys, isNodeOfType } from 'roosterjs-content-model-dom';
import type { CreateElementData } from './CreateElementData';
 
/**
 * @internal
 * Create DOM element from the given CreateElementData
 * @param elementData The CreateElementData or an index of a known CreateElementData used for creating this element
 * @param document The document to create the element from
 * @returns The root DOM element just created
 */
export function createElement(elementData: CreateElementData, document: Document): Element | null {
    if (!elementData || !elementData.tag) {
        return null;
    }
 
    const { tag, namespace, className, style, dataset, attributes, children } = elementData;
    const result = namespace
        ? document.createElementNS(namespace, tag)
        : document.createElement(tag);
 
    if (style) {
        result.setAttribute('style', style);
    }
 
    if (className) {
        result.className = className;
    }
 
    if (dataset && isNodeOfType(result, 'ELEMENT_NODE')) {
        getObjectKeys(dataset).forEach(datasetName => {
            result.dataset[datasetName] = dataset[datasetName];
        });
    }
 
    if (attributes) {
        getObjectKeys(attributes).forEach(attrName => {
            result.setAttribute(attrName, attributes[attrName]);
        });
    }
 
    if (children) {
        children.forEach(child => {
            if (typeof child === 'string') {
                result.appendChild(document.createTextNode(child));
            } else if (child) {
                const childElement = createElement(child, document);
                Eif (childElement) {
                    result.appendChild(childElement);
                }
            }
        });
    }
 
    return result;
}