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>
5
  • It works if you don't wrap your HTML in a script tag needlessly. Commented Oct 20, 2020 at 18:18
  • 2
    What are you trying to achieve placing HTML inside a script tag with type as html? Just curious Commented Oct 20, 2020 at 18:19
  • More on HTML "scripts" Commented Oct 20, 2020 at 18:20
  • @ Josh Bonnick: stackoverflow.com/questions/7096820/html-tag-inside-javascript Commented Oct 20, 2020 at 18:23
  • 1
    To what in that lengthy page are you referring us? Commented Oct 20, 2020 at 18:24

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

A big bravo Quentin !!! Very clear and surprisingly so quick as an answer !!! Thank you a lot

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.