Search code examples
javascripthtmlinnerhtml

Using innerHTML for partial HTML


the following function

<script>
function new_par()
{
var beginning="<input id=";
document.getElementById("debug").innerHTML=beginning;
}
</script>

produces no output, although if I remove the "<" sign, it does. Presumably the javascript avoids an output that would destroy the html page, but would there be anyway to force the output?


Solution

  • You're assigning it to a node's innerHTML property. When you plug the string into the DOM it's trying to parse it as though it were HTML. If you were to simply add it as a text node it would appear.

    var beginning="<input id=''";
    document.body.textContent = beginning;
    

    https://jsfiddle.net/2patzyo1/

    Edit: upon looking again at your question, if you are trying to get the input element to appear on the page, the string you're using isn't proper HTML because you never closed the tag. When the browser runs into it, it tries to parse and render it, but because it isn't valid it gives up. This will work:

    var beginning="<input id=''>";
    document.body.innerHTML = beginning;
    

    https://jsfiddle.net/2patzyo1/1/