All files / utils htmlToDom.ts

100% Statements 6/6
100% Branches 4/4
100% Functions 2/2
100% Lines 6/6

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                8x 1x     7x 7x 7x                     3x    
// https://github.com/fregante/doma/blob/master/index.ts
 
/**
 * 将 HTML 字符串转为 DocumentFragment。
 *
 * @param html HTML 字符串
 */
export function htmlToDocumentFragment(html: string): DocumentFragment {
  if (html == null) {
    return new DocumentFragment()
  }
 
  const template = document.createElement('template')
  template.innerHTML = html
  return template.content
}
 
/**
 * 将 HTML 字符串转为 Element。
 *
 * @param html HTML 字符串
 */
export function htmlToElement<T extends Element = Element>(
  html: string,
): T | undefined {
  return (htmlToDocumentFragment(html).firstElementChild as T) ?? undefined
}