'Javascript Document Write Inquiry

I have been trying many times to write a code using JavaScript events, so I thought that JavaScript's document.write will be somehow similar to PHP's echo. Is there any way to force document.write to perform an inline write similar to PHP's echo?

The sample: Situation

My website

<input type="text" id="inputText" onchange="writeText()">

Script

<script>
function writeText(){document.write(document.getElementById("inputText").value);}
</script>

I want it to act like every time you change the value of the text box, it will display the value of the textbox just below the text box where it came from or much nicer have it executed by using PHP's echo with some how like this:

<script>
var inputs = document.getElementById("inputText").value;
function writeText(){document.write("<"."?php "."echo '".inputs."';"."?".">");}
</script>

Note: please don't use elements to catch the values, I know it but what I want to aim here is to write inline with document.write without deleting the other contents of the page.



Solution 1:[1]

document.write() is not designed for use from event handlers because if the current document has already finished loading (which it has when an event fires), then document.write() first clears the current document and then adds new content to the empty document.

To add content to a document after it has already loaded, you need to either modify the innerHTML of an existing element or create new elements and programmatically add them to the page.

In your question, it is not clear where you want the writeText() function to put the content that it generates, but here's an example of append some new content into a document at a particular location in the document.

function writeText(parentElem, newHTML) {
    var elem = document.createElement("span");
    elem.innerHTML = newHTML;
    parentElem.appendChild(elem);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jfriend00