0

Maybe this is a naive question but I wonder if there is a way to enter a value in a "text/html" script via another script, something like the following example which, by the way, does not work for me.

<script id="Block" type="text/html">
<input type="text" id="InputID"/>
</script>

<script>
document.getElementById('InputID').value = 'some text';
</script>
Apostolos
  • 598
  • 1
  • 5
  • 13

1 Answers1

3

Setting the type of a <script> element to text/html is a hack for including some HTML source code in an HTML document without it being rendered so that you can later read the script element and do something with the HTML source code.

const raw_html = document.querySelector("script[type='text/html']").textContent;

This works because normal HTML rules do not apply to a script element, < has no special meaning there (in HTML 4 terms, the script element contains CDATA).

The modern equivalent is the <template> element.

You have no <input> element, so you can't find it in the DOM and you can't set a value to it.

If you want to do that, you first need to add it to the DOM.

const raw_html = document.querySelector("script[type='text/html']").textContent;
const container = document.querySelector("#container");
container.innerHTML = raw_html;
document.getElementById('InputID').value = 'some text';
<script id="Block" type="text/html">
<input type="text" id="InputID"/>
</script>

<div id="container"></div>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335