How to usethe DOMParser in Javascript
The DOMParser is an API in JavaScript that allows you to parse HTML strings and create a DOM document from it. It provides a way to programmatically create and manipulate HTML documents in memory.
Example: In this example, we are using DOMParser
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title > Create an element from a string </ title > </ head > < body > < h1 style = "color:green" > w3wiki </ h1 > < script > // Create a string representing the element const elementString = `< div id = "myElement" >This heading is created by using DOMParser</ div >`; // Create a new DOMParser const parser = new DOMParser(); // Parse the element string const doc = ] parser.parseFromString(elementString, 'text/html'); // Access the parsed element const element = doc.body.firstChild; // Now you can manipulate or append the element to the document document.body.appendChild(element); </ script > </ body > </ html > |
Output:
How to create an element from a string in JavaScript ?
In this article, we will learn how to create an element from a string using JavaScript. This can be used in situations where dynamically generated elements are required by the user.
This can be achieved using many approaches as given below:
Table of Content
- Using the createElement() method
- Using the DOMParser
- Using the jQuery parseHTML() method
- Using innerHTML