Home >Web Front-end >JS Tutorial >How to Create DOM Elements from HTML Strings (Multiple Methods)
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.
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
Additionally, this method will not execute any scripts in the HTML string, which is safer when dealing with untrusted content.
const template = document.createElement('template'); template.innerHTML = `<div>Hello World</div>`; const node = template.content.firstElementChild;
The advantage of using the tag is that it has no content restrictions and can contain any type of HTML structure, including table-related elements like This method is similar to innerHTML and can only handle valid HTML nodes. It also will not execute scripts. This method parses the string by creating a full HTML document and then extracts the node from the document. This means it is relatively slower than other solutions and is not recommended for use. It can only handle valid HTML nodes and will not execute scripts. This method is possibly the simplest. It also can only handle valid HTML nodes by default. However, we can set the context to avoid this. Note that it will execute scripts in the HTML string, so be especially careful when dealing with untrusted content, such as using a cleaner like DOMPurify. For different cases, you might need to choose the method that works best for you. If you find my content helpful, please consider subscribing. I send a daily newsletter with the latest web development updates. Thanks for your support! The above is the detailed content of How to Create DOM Elements from HTML Strings (Multiple Methods). For more information, please follow other related articles on the PHP Chinese website! and .
insertAdjacentHTML
const container = document.createElement("div");
container.insertAdjacentHTML("afterbegin", `<div>Hello World</div>`);
const node = container.firstElementChild;
DOMParser
const node = new DOMParser().parseFromString(`<div>Hello World</div>`, "text/html").body.firstElementChild;
Range.createContextualFragment
const node = document.createRange().createContextualFragment(`<div>Hello World</div>`).firstElementChild;
Conclusion
Related articles
See more