innerHTML manipulation in JavaScript

htmljavascript

The innerHTML property in JavaScript allows you to get or set the HTML content of an element. It can be useful for dynamically updating the content of a page or for creating new elements on the fly.

To get the innerHTML of an element, you can use the .innerHTML property of the element. For example:

let element = document.getElementById('my-element');
let html = element.innerHTML;

This will store the HTML content of the element with the ID my-element in the html variable.

To set the innerHTML of an element, you can use the .innerHTML property as well. For example:

let element = document.getElementById('my-element');
element.innerHTML = '<p>Hello World</p>';

This will replace the current HTML content of the element with a p element containing the text “Hello World”.

Note that setting the innerHTML of an element can be a powerful but potentially dangerous operation. It can overwrite any existing content and can potentially execute malicious code if the HTML content is not sanitized or properly escaped. It is important to be careful when using innerHTML and to ensure that the content is safe and cannot be used to inject harmful code.

For more information on the innerHTML property, you can refer to the JavaScript documentation: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML.