views:

7808

answers:

2

I'm trying to create an element dynamically using an HTML string. Here's a simple example using both prototype and DOM:

// HTML string
var s = '<li>text</li>';
// DOM
var el1 = document.createElement(s);
// prototype
var el2 = new Element(s);
$('mylist').appendChild(el1);
$('mylist').appendChild(el2);

Both approaches insert an empty listitem to the list.

I know that using prototype's Element as a constructor requires a tagName and an optional attributes parameter, but I figured it may let me pass in an HTML string too.

However, MSDN states "You can also specify all the attributes inside the createElement method by using an HTML string for the method argument."... so I'm not sure what the problem is.

And yes, i know i could do this easily in jquery, unfortunately we're not using jquery. Am i overlooking something really simple here?

+10  A: 

Should be obv but the link to that MSDN article is regarding an IE only feature.

Generally the following cross-browser trick is what all the libraries do to get DOM elements from an html string (with some extra work for IE [not shown here], to do with table related html strings like <td>s, <tr>s, <thead>s, etc):

// HTML string
var s = '<li>text</li>';

var div = document.createElement('div');
div.innerHTML = s;
var elements = div.childNodes;

Or var element = div.firstChild if you know you're getting a single root node.

I would recommend you stick to the library-approved method of creating elements from HTML strings though. Prototype has this feature built-into it's update() method.

Crescent Fresh
thanks, that's exactly what i was looking for.
ob
That's a pretty neat trick!
Karl
Does someone know the "extra work for IE [not shown here], to do with table related html strings like <td>", that's exactly what I need! :-) thanks in advance.
Ariel
@Ariel: see http://stackoverflow.com/questions/1848588/why-does-html-work-and-not-innerhtml-or-appendchild/1849100#1849100
Crescent Fresh
+5  A: 

With Prototype, you can also do:

HTML:

<ul id="mylist"></ul>

JS:

$('mylist').insert('<li>text</li>');
Boro