How to Append HTML to the Body Using JavaScript?

Estimated read time 2 min read

To append HTML to the body element using JavaScript, you can create a new HTML element and set its content using the innerHTML property, then append it to the body using the appendChild() method. Here’s an example:

// Create a new HTML element with some content
const newElement = document.createElement('p');
newElement.innerHTML = 'This is some <strong>HTML</strong> code.';

// Append the new element to the body

In this example, createElement('p') creates a new p element, and innerHTML is used to set its content. The appendChild() method is then used to append the new element to the body of the document.

You can modify the HTML content of the new element by changing the value of the innerHTML property before appending it to the body. You can also modify other attributes or properties of the new element before appending it, depending on the type of element and the behavior you want to achieve.

Note that appending raw HTML to a page can be a security risk if the content is not sanitized or validated, especially if the content is user-generated. It’s important to validate or sanitize any user input before appending it to the page to avoid security vulnerabilities such as cross-site scripting (XSS) attacks.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply