Home > Web Front-end > JS Tutorial > How to Create DOM Elements from HTML Strings (Multiple Methods)

How to Create DOM Elements from HTML Strings (Multiple Methods)

PHPz
Release: 2024-08-01 20:18:42
Original
1190 people have browsed it

When we need to create simple dynamic HTML DOM elements, we can use HTML string templates. There are many different methods to achieve this in JavaScript, but we might have some considerations.


innerHTML

How to Create DOM Elements from HTML Strings (Multiple Methods)

const container = document.createElement('div');
container.innerHTML = `<div>Hello World</div>`;
const node = container.firstElementChild;
Copy after login

This is one of the most common methods. Insert the HTML string into the innerHTML of a container element, and then access the generated DOM node.

However, it can only handle valid HTML nodes, i.e., elements that are legal in standard HTML structures. For example, if you try to insert a element into a

, the node will not be created.

How to Create DOM Elements from HTML Strings (Multiple Methods)

Additionally, this method will not execute any scripts in the HTML string, which is safer when dealing with untrusted content.

innerHTML + template Element

How to Create DOM Elements from HTML Strings (Multiple Methods)

const template = document.createElement('template');
template.innerHTML = `<div>Hello World</div>`;
const node = template.content.firstElementChild;
Copy after login

The advantage of using the