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

How Can I Convert HTML Strings into DOM Elements in JavaScript?

Barbara Streisand
Release: 2024-11-21 05:26:14
Original
724 people have browsed it

How Can I Convert HTML Strings into DOM Elements in JavaScript?

Creating DOM Elements from HTML Strings

In JavaScript, there are instances when you need to convert HTML strings into their corresponding DOM elements. This is a fundamental operation for dynamically creating and manipulating the page's content, such as when appending elements to the document.

To accomplish this task, you can utilize a DOMParser. The syntax for using DOMParser is:

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

Here, htmlString represents the HTML code you wish to convert, and doc is the resulting document containing the parsed DOM elements.

For instance, consider the following HTML string:

<div>
    <a href="#"></a>
    <span></span>
</div>
Copy after login

Using the DOMParser, you can convert this string into a DOM element as follows:

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

The doc object now holds the parsed HTML as a DOM element, which can be appended to the page using methods like appendChild():

const parentElement = document.getElementById('parent');
parentElement.appendChild(doc.firstChild);
Copy after login

This will add the parsed HTML content as a child element of the parentElement in the actual DOM. Note that DOMParser interprets XHTML-style HTML, which requires closing tags, as in the example above.

The above is the detailed content of How Can I Convert HTML Strings into DOM Elements 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