How to Display HTML Content Using JavaScript?

Estimated read time 1 min read

Displaying HTML content using JavaScript can be done by modifying the innerHTML or textContent property of an HTML element.

Here’s an example of how to display a simple HTML paragraph in an HTML element with an id of “content”:

<!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <div id="content"></div>
    <script>
      let contentElement = document.getElementById("content");
      contentElement.innerHTML = "<p>This is a simple paragraph.</p>";
    </script>
  </body>
</html>

In this example, we first use JavaScript to select an HTML element with an id of “content”. We then modify the innerHTML property of the element to set its content to a simple HTML paragraph.

It’s important to note that when you use innerHTML to insert HTML content, you should make sure that the content is properly escaped to prevent security vulnerabilities. You can use a library such as DOMPurify to sanitize untrusted HTML.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply