Create new DOM elements from HTML strings using built-in DOM methods or prototypes

I have an HTML string representing the element: '< li > text < / Li >'. The elements I want to attach to the DOM (in my case, ul). How can I do this using the Prototype or DOM methods?

(I know I can do this easily in jQuery, but unfortunately we didn't use jQuery.)

#1 building

This will also work:


It feels more like a jquery with linked function calls.

#2 building

var jtag = ${ child:'text' }); // Represents: <li>text</li>
var htmlContent = $('mylist').html();
$('mylist').html(htmlContent + jtag.html());

Use jnerator

#3 building

Late, but only as notes;

You can add a trivial element to the target element as a container and remove it after use.

//It was tested on chrome 23.0, firefox 18.0 (i.e. 7-8-9 and Opera 12.11).

<div id="div"></div>

window.onload = function() {
    var foo, targetElement = document.getElementById('div')
    foo = document.createElement('foo')
    foo.innerHTML = '<a href="#" target="_self">Text of A 1.</a> '+
                    '<a href="#" onclick="return !!alert(this.innerHTML)">Text of <b>A 2</b>.</a> '+
                    '<hr size="1" />'
    // Append 'foo' element to target element

    // Add event
    foo.firstChild.onclick = function() { return !!alert( }

    while (foo.firstChild) {
        // Also removes child nodes from 'foo'
        targetElement.insertBefore(foo.firstChild, foo)
    // Remove 'foo' element from target element

#4 building

This is a simple way:

  var d=document
  return b;

var foo="<img src='//'>foo<i>bar</i>".toDOM();

#5 building

For this problem, I think I will come up with some complex but simple methods. Maybe someone will find something useful.

/*Creates a new element - By Jamin Szczesny*/
function _new(args){
    ele = document.createElement(args.node);
    delete args.node;
    for(x in args){ 
        if(typeof ele[x]==='string'){
            ele[x] = args[x];
            ele.setAttribute(x, args[x]);
    return ele;

/*You would 'simply' use it like this*/

    style:'position:absolute; left:100px; top:100px;'+
          'width:100px; height:100px; border:2px solid red;'+
          'cursor:pointer; background-color:HoneyDew',
    innerHTML:'My newly created div element!',
    value:'for example only',

Keywords: JQuery Firefox

Added by dlester on Fri, 10 Jan 2020 17:24:54 +0200