Say I want to print html from inside a script tag.
A source like this
foo
You can use
function echo(content) {
var e = document.createElement("p");
e.innerHTML = content;
document.currentScript.parentElement.replaceChild(document.currentScript, e);
}
which will replace the currently executing script who called the echo function with the text in the content argument.
// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if(this.console){
console.log( Array.prototype.slice.call(arguments) );
}
};
Using window.log will allow you to perform the same action as console.log, but it checks if the browser you are using has the ability to use console.log first, so as not to error out for compatibility reasons (IE 6, etc.).
this is an another way:
<html>
<head>
<title>Echo</title>
<style type="text/css">
#result{
border: 1px solid #000000;
min-height: 250px;
max-height: 100%;
padding: 5px;
font-family: sans-serif;
font-size: 12px;
}
</style>
<script type="text/javascript" lang="ja">
function start(){
function echo(text){
lastResultAreaText = document.getElementById('result').innerHTML;
resultArea = document.getElementById('result');
if(lastResultAreaText==""){
resultArea.innerHTML=text;
}
else{
resultArea.innerHTML=lastResultAreaText+"</br>"+text;
}
}
echo("Hello World!");
}
</script>
</head>
<body onload="start()">
<pre id="result"></pre>
</body>
You can use document.write
or even console.write
(this is good for debugging).
But your best bet and it gives you more control is to use DOM to update the page.
We would create our own function in js like echo "Hello world".
function echo( ...s ) // rest operator
{
for(var i = 0; i < s.length; i++ ) {
document.write(s[i] + ' '); // quotes for space
}
}
// Now call to this function like echo
echo('Hellow', "World");
Note: (...
) rest operator dotes for access more parameters in one as object/array, to get value from object/array we should iterate the whole object/array by using for loop, like above and s
is name i just kept you can write whatever you want.
You need to use document.write()
<div>foo</div>
<script>
document.write('<div>Print this after the script tag</div>');
</script>
<div>bar</div>
Note that this will only work if you are in the process of writing the document. Once the document has been rendered, calling document.write()
will clear the document and start writing a new one. Please refer to other answers provided to this question if this is your use case.