You can create a new html element by appending element text to an existing element, such as this:

const elementText = "<p>hello, world</p>";
const newElement = document.createElement("div");
newElement.innerHTML = elementText
document.body.appendChild(newElement);

This will create a new paragraph element with the text "hello world".

But if you use the innerHTML method for element creation you can expose the application to a script injection. For example:

const elementText = "<img src=1 onerror=alert('xss exploit')>";
const newElement = document.createElement("div");
newElement.innerHTML = elementText
document.body.appendChild(newElement);

In the case were you don't control the value of the HTML you are creating you need to be careful to allow injection to occur.

To protect our application from this XSS attack we shouldn't use `innerhtml` to create the element but create an element and use the `textContent` property. Taking our first example, it would look as so:

const elementText = "hello, world";
const newElement = document.createElement("div");
const paragraph = document.createElement("p");
paragraph.textContent = elementText;
newElement.appendChild(paragraph);
document.body.appendChild(newElement);

And in the case where our input attempts to exploit xss we would get:

const elementText = "<img src=1 onerror=alert("xss exploit")>";
const newElement = document.createElement("div");
const paragraph = document.createElement("p");
paragraph.textContent = elementText;
newElement.appendChild(paragraph);
document.body.appendChild(newElement);

Did this answer your question?