Skip to content

Instantly share code, notes, and snippets.

@Sanchithasharma
Last active January 26, 2022 14:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sanchithasharma/8ab572ac877f3856fce12eb78b29acc6 to your computer and use it in GitHub Desktop.
Save Sanchithasharma/8ab572ac877f3856fce12eb78b29acc6 to your computer and use it in GitHub Desktop.
Convert HTML text to plain text using temporary DOM element
function convertToPlain(html){
// Create a new div element
var tempDivElement = document.createElement("div");
// Set the HTML content with the given value
tempDivElement.innerHTML = html;
// Retrieve the text property of the element
return tempDivElement.textContent || tempDivElement.innerText || "";
}
var htmlString= "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute</p></div>";
console.log(convertToPlain(htmlString));
// Expected Result:
// Bears Beets Battlestar Galactica
// Quote by Dwight Schrute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment