DEV Community

Guilherme Siquinelli
Guilherme Siquinelli

Posted on

2

DOM Parser, parse de string para elementos DOM

Faça conversão de código XML ou HTML a partir de texto (string) para um documento DOM

Como funciona

A execução pode ser feita para XML ou HTML, de acordo com o tipo e retornará como resultado um documento (Document). O tipo é informado como parâmetro e são aceitas as opções "text/html" , que por sua vez, invocará o parser HTML ou então "text/xml", "application/xml", "application/xhtml+xml" e "image/svg+xml", qualquer uma das anteriores invocará o parser XML.

Para o parser XML, caso a string não possa ser processada, o documento retornado deverá conter elementos descrevendo do erro retornado.

💬 Note
Scripts não são executados durante o processamento e o resultado sempre será no formado UTF-8.

Caso seja informado um tipo diferente dos mencionados acima, uma exceção TypeError será retornada.

Interface

type DOMParserSupportedType =
    | "application/xhtml+xml"
    | "application/xml"
    | "image/svg+xml"
    | "text/html"
    | "text/xml";

interface DOMParser {
    parseFromString(string: string, type: DOMParserSupportedType): Document;
}
Enter fullscreen mode Exit fullscreen mode

Exemplos

Texto para elementos HTML

export function parseToHTML(value: string) {
    const parser = new DOMParser()
    return parser.parseFromString(value, 'text/html')
}
Enter fullscreen mode Exit fullscreen mode

Texto para elementos SVG

export function parseToSVG(value: string) {
    const parser = new DOMParser()
    return parser.parseFromString(value, 'image/svg+xml')
}
Enter fullscreen mode Exit fullscreen mode

Casos de uso

Vamos supor que eu esteja usando Vite em um projeto e quero criar componentes da web nativos e, os templates ficarão em arquivos separados, algo como isso:

src/elements
├── form
│   ├── control.html
│   ├── control.ts
│   ├── error.html
│   ├── error.ts
│   ├── label.html
│   └── label.ts
Enter fullscreen mode Exit fullscreen mode

Fazendo import de arquivos HTML, ele é recebido como string

import textTemplate from './error.html?raw'

console.log(typeof textTemplate);
// string
Enter fullscreen mode Exit fullscreen mode

Meu arquivo HTML usa o elemento template, então, antes de inserir ao shadowRoot, eu quero encontrar o template usando querySelector e depois clonar o elemento. Para que a busca funcione, precisamos que sejam elementos DOM, correto?

Desta forma eu poderia fazer:

const shadow = this.attachShadow({ mode })
const docTemplate = parseToHTML(textTemplate)
const template = docTemplate.querySelector('template')
shadow.appendChild(template.content.cloneNode(true))
Enter fullscreen mode Exit fullscreen mode

Espero ter ajudado, valeu!
[]s

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️