DOMParser
DOMParser is used for converting strings into DOM elements aka. parsing HTML string into a structured document using
the parseFromString method and it will return a Document object which we can then use adoptNode to transfer a node
from one document to another or use cloneNode to create a copy of a node within a document.
It’s similar to innerHTML but it’s safer as it doesn’t run the JS Code inline of the string which allows also to do
transformations before appendChild it to the current Document.
1// Create an HTML string
2const htmlString = "<div><p>Hello, DOMParser!</p></div>";
3
4// Create a new DOMParser
5const parser = new DOMParser();
6
7// Use the parseFromString method to parse the HTML string
8const parsedDocument = parser.parseFromString(htmlString, "text/html");
9
10// Get the first element from the parsed document
11const parsedNode = parsedDocument.body.firstChild;
12
13// Get the parent element in the current document where the parsed node will be appended
14const parentElement = document.getElementById("parent");
15
16// Adopt the parsed node to the current document
17const adoptedNode = document.adoptNode(parsedNode);
18
19// Append the adopted node to the parent element
20parentElement.appendChild(adoptedNode);Read more: