Recommended: Element.append()
You can create an element using document.createElement()
.
That element can then be appended to document.body
.
// Create an <img>-element
var img = document.createElement('img');
// Configure the attributes of your element
img.alt = 'An alternative text';
// Append it
document.body.append(img);
Element.innerHTML
You can add the String directly to the HTML using Element.innerHTML
. However, as mentioned in the link, that makes your site vulnerable to script-execution when a script is inserted without using the <script>
-tag.
Example of the vulnerability (hover over the image-element to see its effect):
var altText = 'some text" onmouseover="(() => {console.log(\'This lambda was executed!\')})()';
// This will add the following:
// <img alt="some text" onmouseover="(() => {console.log('This lambda was executed!')})()">
document.body.innerHTML += '<img alt="' + altText + '">';
But if you are sure that the string you build is safe, you can add the contained element like this (replace the String-placeholder below with your String):
document.body.innerHTML += '<img alt="Some text">';
<p>I was here first!</p>