Search code examples
javascriptdomprototypejs

Insert innerHTML with Prototypejs


Say I have a list like this:

<ul id='dom_a'>
  <li>foo</li>
</ul>

I know how to insert elements in the ul tag with:

Element.insert('dom_a', {bottom:"<li>bar</li>"});

Since the string I receive contains the dom id, I need to insert the inner HTML instead of the whole element. I need a function to do this:

insert_content('dom_a', {bottom:"<ul id='dom_a'><li>bar</li></ul>"});

And obtain:

<ul id='dom_a'>
  <li>foo</li>
  <li>bar</li>
</ul>

How should I do this with Prototype ?

Here is the solution I have come up with, can anyone make this better ?

Zena.insert_inner = function(dom, position, content) {
  dom = $(dom);
  position = position.toLowerCase();
  content = Object.toHTML(content);
  var elem = new Element('div');
  elem.innerHTML = content; // strip scripts ?
  elem = elem.down();
  var insertions = {};
  $A(elem.childElements()).each(function(e) {
    insertions[position] = e;
    dom.insert(insertions);
  });
}

Solution

  • I think you can slim down the code a bit by simply appending the innerHTML of the first child of temporary element:

    Zena.insert_inner = function(dom, position, content) {
        var d = document.createElement('div');
        d.innerHTML = content;
        var insertions = {};
        insertions[position] = d.firstChild.innerHTML;
        Element.insert(dom, insertions);
    }
    

    Not too much of an improvement though, example here.