Flat Preloader Icon

JS inner HTML Property

The innerHTML property in JavaScript is used to get or set the HTML content (including tags) of an element. It allows you to dynamically manipulate the HTML structure and content of an element directly from JavaScript.

Getting HTML Content:

  • To retrieve the HTML content of an element, you can simply access its innerHTML property. It returns a string representing the HTML content of the element, including its child elements and text nodes.
				
					let element = document.getElementById("example");
let htmlContent = element.innerHTML;
console.log(htmlContent);

				
			

Setting HTML Content:

  • To set the HTML content of an element, you can assign a string containing valid HTML markup to its innerHTML property. This will replace the existing content of the element with the new HTML content.
				
					let element = document.getElementById("example");
element.innerHTML = "<p>New content</p>";

				
			

Example Usage:

				
					<!DOCTYPE html>
<html>
<head>
    <title>innerHTML Property 
    Example</title>
</head>
<body>
    <div id="example">
        <p>Initial content</p>
    </div>

    <button onclick="changeContent()">
        Change Content</button>

    <script>
        function changeContent() {
            let element = document.getElementById
            ("example");
            element.innerHTML = "<p>New content</p>";
        }
    </script>
</body>
</html>

				
			

Note:

  • When setting the innerHTML, the browser parses the provided string as HTML and updates the element’s content accordingly. Any existing content within the element will be replaced.
  • Care should be taken when using innerHTML to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. Avoid inserting untrusted or user-generated content directly into innerHTML to mitigate this risk.
  • Setting innerHTML on certain elements (such as <script> or <style>) may have unexpected behavior, so it’s generally recommended to use other methods for inserting scripts or styles dynamically.

Compatibility:

  • The innerHTML property is widely supported in all modern browsers and versions of Internet Explorer (including IE6+).