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

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

PHPz
PHPzOriginal
2024-08-01 20:18:421123browse

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;

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;

The advantage of using the