0
This property is used to add some content inside some element in the document, for example.
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
</head>
<body>
<p id="paragraph"></p>
<script>
let p = document.querySelector("#paragraph");
p.innerHTML = "Esse é um parágrafo!";
</script>
</body>
</html>
Or else some HTML element like, lists.
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
</head>
<body>
<p id="paragraph"></p>
<script>
let p = document.querySelector("#paragraph");
p.innerHTML = "<ul><li>Lista 1</li><li>Lista 2</li><li>Lista 3</li></ul>";
</script>
</body>
</html>
But when trying to insert the element script
with some code, it just doesn’t work! case the closing tag includes a bar will return error.
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
</head>
<body>
<p id="paragraph"></p>
<script>
let p = document.querySelector("#paragraph");
p.innerHTML = "<script>alert('Essa é uma caixa!')<script>";
</script>
</body>
</html>
Why is the script not running? would be for security reasons?
You have to use an escape sequence in the tag and the property to set to replace the element is
outerHTML
. Would look like this:p.outerHTML = "<script>alert('Essa é uma caixa!')<\/script>";
replace in the document but the script would not be executed. To run the script has to be added either by DOM or withdocument.write
howeverdocument.write
implies the document reload. This is because the browser imposes a layer of isolation between visual components and code, nothing to do with safety.– Augusto Vasques