Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript inline output

In javascript suppose you have this piece of code:

<div>
    <script type="text/javascript">var output = 'abcdefg';</script>
</div>

Is there any way to simply "echo" (using PHP terminology) the contents of output into #test? That is, to output a string inline, assuming you have no standard way of traversing or selecting from the DOM?

document.write("..."); does write the contents of output, but in doing so, it replaces the entire document with the output.

The solution I'm looking for should act the same way a PHP echo would: write the output into the document inline.

like image 455
dclowd9901 Avatar asked Jul 04 '11 00:07

dclowd9901


2 Answers

You'd have to use document.write [docs]:

<div id="test">
    <script type="text/javascript">document.write('abcdefg');</script>
</div>  

DEMO

With the caveat that it does not work in XHTML documents. See the documentation for more details.

like image 169
Felix Kling Avatar answered Oct 08 '22 23:10

Felix Kling


In standards-based browsers:

document.getElementByID("test").textContent = output;

For broader support, you could use text in jQuery (or the equivalent method if your library of choice):

$('#test').text(output);
like image 43
Matthew Flaschen Avatar answered Oct 09 '22 01:10

Matthew Flaschen