Converting Raw HTML Strings to DOM Elements for Appending
JavaScript provides various ways to manipulate HTML content, including modifying the innerHTML or innerText properties of DOM elements. However, sometimes it is necessary to convert a raw HTML string into a DOM element to use with methods like appendChild().
Using DOMParser
The DOMParser interface allows parsing XML and HTML strings into DOM elements. To convert a raw HTML string into a DOM element using DOMParser:
var xmlString = "<div><a href='#'>Link</a><span></span></div>"; var doc = new DOMParser().parseFromString(xmlString, "text/xml");
The parseFromString() method parses the HTML string and returns a Document object containing the parsed DOM structure.
Accessing DOM Elements
To access individual DOM elements within the parsed document:
console.log(doc.firstChild.innerHTML); // Outputs: <a href='#'>Link...</a> console.log(doc.firstChild.firstChild.innerHTML); // Outputs: Link
Usage
The parsed DOM element can now be passed to appendChild() or used for other DOM manipulation tasks, such as:
var parentElement = document.getElementById("container"); parentElement.appendChild(doc.firstChild);
This will effectively append the parsed HTML string as a DOM element to the #container element.
Note: It's important to use appendChild() with the parsed DOM element obtained via DOMParser, rather than directly appending the raw HTML string, as the latter can result in security vulnerabilities.
The above is the detailed content of How Can I Safely Append Raw HTML Strings to the DOM in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!