Home > Web Front-end > JS Tutorial > How Can I Safely Append Raw HTML Strings to the DOM in JavaScript?

How Can I Safely Append Raw HTML Strings to the DOM in JavaScript?

Susan Sarandon
Release: 2024-11-19 05:05:02
Original
859 people have browsed it

How Can I Safely Append Raw HTML Strings to the DOM in JavaScript?

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");
Copy after login

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
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template