DEV Community

Discussion on: 3 ways to convert HTML text to plain text

Collapse
etienneburdet profile image
Etienne Burdet • Edited on

There is an alternative to create a DOM element that doesn't append to the body (actually the one from OP doesn't either!) :

 

const parser = new DOMParser()
const floatingElement = parser.parseFromSrting(stringWithTags, 'text/xml')
const string = floatingElement.innerText
Enter fullscreen mode Exit fullscreen mode

You could also use document.createDocumentFragment(string), but fragment have no innerText, so in the end it's more complicated.

Collapse
mellen profile image
Matt Ellen

The method presented in the main post doesn't append to the body, either.

Collapse
etienneburdet profile image
Etienne Burdet • Edited on

Ho you're right, I read that too quickly :p