Home > Web Front-end > JS Tutorial > How Can I Create DOM Elements from HTML Strings in JavaScript?

How Can I Create DOM Elements from HTML Strings in JavaScript?

Patricia Arquette
Release: 2024-12-02 09:25:10
Original
821 people have browsed it

How Can I Create DOM Elements from HTML Strings in JavaScript?

Creating DOM Elements from HTML Strings

The query explores the feasibility of converting HTML strings into DOM elements that can be appended to a parent element using appendChild(). While other methods like innerHTML and innerText exist, they don't provide the level of flexibility and control desired.

In JavaScript, you can utilize a DOMParser to achieve this conversion. This parser takes an HTML string as input and generates a document object representing the HTML content. The parsed document can then be accessed to obtain the corresponding DOM elements.

For instance, consider the following HTML string stored as a JavaScript variable:

const htmlString = "<div><a href='#'>Link</a><span></span></div>";
Copy after login

To transform this string into a DOM element, you can use the following code:

const doc = new DOMParser().parseFromString(htmlString, "text/xml");
const firstChildElement = doc.firstChild;
Copy after login

firstChildElement now represents the

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