views:

74

answers:

4

I need to give the user a snippet of js code that will insert some HTML code into the page.

I'm wondering what the best method to do so is. Should I use document.write, should I just create all the HTML elements via DOM programmatically?

Is it possible to use a js library? I can see conflicts occurring if the webpage the code is embedded in already contains the library.

+4  A: 

Using a library is probably too heavyweight, inserting DOM elements is very verbose and document.write may not work if the target site uses the application/xhtml+xml content type. I think your best bet is to construct one element using document.createElement and then setting innerHTML on that.

Raphael Schweikert
A: 

If its simple insertion you can use pure js, otherwise if you want to provide some complex functionality you can use library. The best choice in this case will be the lib that does not extend root objects (Array, Function, String) to prevent conflicts (jQuery in noConflict mode, YUI, etc.).

Anyway it will be better to avoid using document.write u'd better use setting of innerHTML of existing element or create new one.

fantactuka
+1  A: 

A suggestion:

Insert this DIV wherever you want the output to appear:

<div id="uniqueTargetID" style="display: none;"></div>

Then at bottom of page have this:

<script src="snippet.js"></script>

This file (remotely hosted or otherwise) contains could output simple text this way:

var html = [];
html.push('<h1>This is a title</h1>');
html.push('<p>So then she said, thats not a monkey, its a truck!</p>');
html.push('<p>You shoulda seen his face...</p>');
var target = document.getElementById('uniqueTargetID');
target.innerHTML = html.join('');
target.style.display = 'block';

I would avoid using document.write() if you can help it.

michael
What happens if the html has single or double quotes in them. Is there a better way to escape js than just replacing " with \"?
rksprst
one nitpick... html.join(''), you'll get a bunch of commas if you leave it as-is.. :)
Tracker1
rksprst: You'll have that problem with any of the solutions proposed here. The answer depends on where your data is coming from, in what form, and how you use that to your advantage.
michael
+1  A: 

Javascript::

//to avoid global bashing
(function(){
  var target = document.getElementById('ScriptName'),
    parent = target.parentElement,
    oput = document.createElement('div');
  oput.innerHTML = "<p>Some Content</p>";
  parent.insertBefore(oput, target);
}());

HTML to give to client/people::

<script type="text/javascript" id="ScriptName" src="/path/to/ScriptName.js"><script>

ScriptName should be something unique to your script.

Rixius