How to Convert HTML to a String in JavaScript?

Estimated read time 2 min read

In JavaScript, you can convert HTML to a string by using the innerHTML property of an HTML element. This property returns the HTML content inside the element as a string.

Here’s a simple example that shows how to convert the HTML content of a div element to a string:

let div = document.getElementById('myDiv');
let htmlString = div.innerHTML;

In this example, the getElementById method is used to retrieve the div element with the ID 'myDiv', and the innerHTML property of the element is assigned to the htmlString variable.

Note that this approach only works for HTML elements that are part of the DOM, and that have already been loaded in the browser. If you need to convert HTML content that is not part of the DOM, you can create a temporary element, set its innerHTML property to the HTML content, and then retrieve the innerHTML property of the temporary element.

Here’s an example that shows how to convert an HTML string to a string in JavaScript:

let html = '<div><p>Hello, World!</p></div>';
let tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
let htmlString = tempDiv.innerHTML;

In this example, the createElement method is used to create a temporary div element, the innerHTML property of the element is set to the HTML content, and then the innerHTML property of the temporary element is retrieved and assigned to the htmlString variable.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply