Nikita Rybak
Nikita Rybak

Reputation: 68006

write html content from javascript

There's one thing I want to do with javascript, but don't know how. In a perfect world it would look like this:

<p>My very cool page!</p>
<script type="text/javascript">
    document.write('<div>some content</div>');
</script>

And this script would insert <div>some content</div> right before (or after, or instead of) script tag. But in the real world, document.write starts writing html anew, removing any static content in the page (<p> tag, in this case).

This is simplified example, but should give you the idea. I know that I can statically put <div id="some_id"></div> before script tag and insert html in it from js, but I wanna be able to use multiple instances of this snippet without changing it (generating random id manually) each time.

I'm ok to use jquery or any other existing library as well. Is there any way to achieve this? Thanks!

Upvotes: 1

Views: 3173

Answers (5)

Nikita Rybak
Nikita Rybak

Reputation: 68006

To close the question, here's how it has worked out in the end.

The trick was to store each widget's data in html tag, not in javascript. User inserts content like this

<div class="my_widget" feed_id="123"></div>
...
<div class="my_widget" feed_id="456"></div>

User also links script from our server. When page's loaded, script does $('div.my_widget').each and populates contents of each widget depending on its feed_id and other attributes.

Thanks to everyone (and +1 to Gaby and Kerry for attempts to help with such vague problem)

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

We are actually in that perfect world...

and your example would work as it is ..

http://www.jsfiddle.net/BtKGV/

Upvotes: 2

Kevin Carmody
Kevin Carmody

Reputation: 2319

look up appendChild()

Upvotes: 0

JYelton
JYelton

Reputation: 36512

You also might want to read about adding and removing elements to/from the DOM, such as in this article:

http://www.dustindiaz.com/add-remove-elements-reprise/

Upvotes: 0

Kerry Jones
Kerry Jones

Reputation: 21838

Yes, but you always add or write it in relation to something else.

If you wanted to write something AFTER the first p tag, in jQuery, you could do something liek this

$('p:first').after( '<div>some content</div>' );

If you look at jQuery's API you will see they have many functions for this, such as before, after, append, etc.

Upvotes: 1

Related Questions