Categories
JavaScript Answers

How to convert an HTML Element to a string with JavaScript?

Spread the love

You can convert an HTML element to a string in JavaScript by accessing its outerHTML property.

The outerHTML property returns the HTML representation of the element, including the element itself and its descendants.

For example we write

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Convert HTML Element to String</title>
</head>
<body>

  <div id="myDiv">
    <p>This is a paragraph.</p>
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
  </div>

  <script>
    // Select the element by ID
    var myDiv = document.getElementById("myDiv");

    // Convert the element to a string
    var htmlString = myDiv.outerHTML;

    // Log the HTML string to the console
    console.log(htmlString);
  </script>

</body>
</html>

In this example, the JavaScript code selects the <div> element with the ID “myDiv” and then retrieves its outerHTML property, which contains the HTML representation of the <div> element and its contents.

Finally, it logs the HTML string to the console.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *