73

Say I want to print html from inside a script tag.

A source like this

<div>foo</div>
<script>
print('<div>Print this after the script tag</div>');
</script>
<div>bar</div>

should look something like this in browser after the script has run

<div>foo</div>
<script>
print('<div>Print this after the script tag</div>');
</script>
<div>Print this after the script tag</div>
<div>bar</div>

I could write my own code for this purpose but since this looks to me like a very simple problem, I'm guessing either I've missed something or my thinking is flawed in some way and printing is left out intentionally.

Also, somewhat related: I'd like to know if a script is (or can be made) aware of the script tags surrounding it. With this information it would be much easier to find the position for the printed html code to be injected into, assuming it's not highly discouraged.

To clarify: I don't need you to write a print function for me. I only need to know if a native method to achieve this exists and I've missed it or alternatively the reason it shouldn't be done.

EDIT I realized that I didn't think the question through.

I got my facts straight and now almost everything seems to be working. I should've originally mentioned that the print function was needed inside templates - I'm working on a template engine experiment. I managed to work it out by separating scripts from plain html and concatenating the split html sans scripts with script output.

As I was writing the code I noticed that everything wouldn't go so smooth because of the asynchronous nature of js. I guess I was expecting to be able to do any kind of js magic in templates, just like I could in php. Seems like actually supporting async code in a fool-proof manner inside templates will require some more thought.

0

9 Answers 9

78

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.

5
  • Ah, I tried document.write() in firebug's script panel and it always cleared the page before writing. It seems to work within the actual page code. Thanks! Commented Nov 29, 2012 at 19:31
  • ...and after a little more testing it still clears the page when called outside the initial page render. Commented Nov 29, 2012 at 19:39
  • 1
    @Pichan: Yes, exactly. While the document is being written, document.write writes into it. Once it's done being written, document.write creates a new document and writes into that. (If you think about it, it makes sense that document.write can't write into an existing complete document. The PHP equivalent would be calling echo after the client has downloaded the whole page and disconnected. Though I admit, the behavior of creating a new document is a bit strange; it might make more sense for it to simply not do anything.)
    – ruakh
    Commented Nov 29, 2012 at 19:50
  • Answer accepted. Although I didn't get what I needed, this was closest to one would guess I was after with my accidentally vague and not-so-well thought question. I'll be updating it tomorrow. Commented Nov 29, 2012 at 21:35
  • -1: Using document.write() is a very bad way to inject content into a page. It blocks page rendering (or as you've discovered resets it). A much better solution is to set the innerHTML of a span or div element.
    – symcbean
    Commented Sep 30, 2015 at 22:38
32

You can use document.write, however it's not a good practice, it may clear the entire page depends on when it's being executed.

You should use Element.innerHtml like this:

<div>foo</div>
<span id="insertHere"></span>
<div>bar</div>

<script>
document.getElementById('insertHere').innerHTML = '<div>Print this after the script tag</div>';
</script>
2
  • 9
    I know this is an old post, but I found that using document.getElementById('element').innerHTML = 'your changes here'; also works and seems simpler to me (just in case anyone else walks in here from a google search like I did..)
    – Partack
    Commented May 30, 2013 at 6:24
  • 2
    @Partack It's a habit, I don't like writing long statement, and by creating a variable I can re-use it later. If you don't need to re-use the element, your style of writing works fine.
    – Lance
    Commented Mar 31, 2015 at 20:40
9

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.

3
  • this works great, but pls modify it a bit: docment => document and remove e.hidden = true; THANKS! Commented Dec 28, 2017 at 13:28
  • 2
    The best answer so far, must definitely be pinned.
    – HolyRandom
    Commented Aug 27, 2020 at 8:55
  • Great answer. <span> instead <p> could be an improvement as <p> may imply default CSS classes Commented Oct 22, 2021 at 21:36
5
// 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.).

3
  • Lol'd at the first paragraph. Sadly I don't need this for debug purposes. Commented Nov 29, 2012 at 19:28
  • 1
    Bummer! (For future viewers: Use this, then to bring up your console in FF, IE, or Chrome, hit F12).
    – Lil' Bits
    Commented Nov 29, 2012 at 19:29
  • 1
    <Ctrl>+<Shift>+<J> in Chrome is preferable over <F12> to me. Commented Mar 27, 2018 at 2:46
1

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>

1

From w3school's page on JavaScript output,

JavaScript can "display" data in different ways:

Writing into an alert box, using window.alert().

Writing into the HTML output using document.write().

Writing into an HTML element, using innerHTML.

Writing into the browser console, using console.log().

0

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.

0
$('element').html('<h1>TEXT TO INSERT</h1>');

or

$('element').text('TEXT TO INSERT');
1
  • 27
    I don't mean to be rude, but this here is a fine example of what I've always said about how jQuery's affects the js coder population. Please at least mention that the code needs jQuery to run. Commented Nov 29, 2012 at 21:32
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.