Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any library that makes create element from string easy?

Tags:

javascript

dom

I need to create an element from this html string:

<li class="station_li">
    <span class="seq_num"></span>
    <a href="javascript:void(0);" class="remove_li_link">delete</a>
</li>  

Now, I have to use:

var li = document.createElement("li");  
li.className = "station_li";  
var span = document.createElement("span");  
span.className............  
............  

this is really boring, is there any js library to make this easier?
NOTE: no jQuery please

like image 917
wong2 Avatar asked Nov 28 '11 11:11

wong2


2 Answers

I often cheat.

function createElmt(html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    return div.childNodes[0];
}
like image 103
Tom van der Woerdt Avatar answered Oct 04 '22 23:10

Tom van der Woerdt


As Tom's solution will not work if the html string consists of siblings, I'd use something like this:

function createElmt(htmlStr) {
  var
    helper = document.createElement('div'),
    result = document.createDocumentFragment(),
    i = 0, num;

  helper.innerHTML = htmlStr;

  for (num = helper.childNodes.length; i < num; i += 1) {
    result.appendChild(helper.childNodes[i].cloneNode(true))
  }

  return result;
}

// test
document.getElementsByTagName('body')[0].appendChild(
  createElmt('<span>1</span> text-node <span>2</span><span>3</span>')
);

Demo: http://jsfiddle.net/zSfdR/

like image 33
Yoshi Avatar answered Oct 04 '22 23:10

Yoshi