How to Append HTML with JavaScript?

Estimated read time 2 min read

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

// Get the element to which the HTML will be appended
const myElement = document.getElementById('my-element');

// 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 existing element

In this example, getElementById('my-element') selects the existing element with the ID of “my-element”. The next two lines create a new p element with some HTML code, and set its content using the innerHTML property. Finally, the appendChild() method is used to append the new element to the existing element.

You can modify the HTML content of the new element by changing the value of the innerHTML property before appending it to the existing element. 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