dom-utils



function isNil(obj:any): boolean {
return typeof obj === "undefined" || obj === null;
}


function fixCls(clsStr: string): string {
if (!clsStr) {
return "";
}

let clsArray = clsStr.split(" ");
clsArray = clsArray.filter((cls) => {
return cls.length > 0;
});
if (clsArray.length === 0) {
return "";
}

clsArray = clsArray.map((cls) => {
if (cls.startsWith("next")) {
return cls;
}
return `SOME_PREFIX_${cls}`;
})

return clsArray.join(" ");
}

const html2EscapeEnums: Record<string, string> = {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;'
};

function html2Escape(sHtml: string) {
return sHtml.replace(/[<>&"]/g, function (c) {
return html2EscapeEnums[c] || c;
});
}

function appendChild(element: HTMLElement, child: any) {
if (isNil(child)) {
return;
} else if (typeof child === "string") {
const txt = html2Escape(child);
const oTxt = document.createTextNode(txt);
element.appendChild(oTxt);
return;
} else if (child instanceof HTMLElement) {
element.appendChild(child);
return;
} else {
const oTxt = document.createTextNode('' + child);
element.appendChild(oTxt);
}
}


function createElement(tagName: string, clazz: string, children?: any) {
const element = document.createElement(tagName);
element.className = fixCls(clazz);
if (!isNil(children)) {
if (Array.isArray(children)) {
for (let i = 0; i < children.length; i++) {
const child = children[i];
appendChild(element, child);
}
} else {
appendChild(element, children);
}
}
return element;
}


function div(clazz: string, children?: any): HTMLElement {
return createElement('div', clazz, children);
}

function span(clazz: string, children?: any): HTMLElement {
return createElement('span', clazz, children);
}

function img(clazz: string, src: string): HTMLElement {
const img = createElement('img', clazz);
img.setAttribute('src', src);
return img;
}

function ifElse(c: boolean, arr: HTMLElement[]): HTMLElement | null {
const a = isNil(arr[0]) ? null : arr[0];
const b = isNil(arr[1]) ? null : arr[1];
return c ? a : b;
}

export {
span,
div,
img,
ifElse
}
posted on 2023-02-11 14:22  袜子破了  阅读(18)  评论(0编辑  收藏  举报