HTML String to DOM

If you have an HTML string and you want to convert it into a Document Object Model (DOM) representation in JavaScript, you can use the DOMParser object. The DOMParser allows you to parse an XML or HTML string and create a DOM object from it. Here's how you can do it:

// Your HTML string
const htmlString = '<div><p>Hello, World!</p></div>';

// Create a new DOMParser instance
const parser = new DOMParser();

// Parse the HTML string
const doc = parser.parseFromString(htmlString, 'text/html');

// Now, doc contains the DOM representation of the HTML string
console.log(doc);

In this example, the parseFromString method of the DOMParser is used to convert the HTML string into a DOM document. The second argument specifies the type of content being parsed, which is 'text/html' in this case.

You can then work with the doc object just like you would with any other DOM document. For instance, you can access elements, modify them, or perform other operations using the standard DOM manipulation methods.

Keep in mind that this code snippet works in browser-based JavaScript environments. If you're working with Node.js, you might need to use a library like jsdom to simulate a browser-like environment for DOM manipulation.

Comments