Is there a library that makes it easy to create an element from a string?

I need to create an element from this html line:

<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............ ............ 

It's really boring, is there a js library to make it easier?
NOTE: no jQuery, please

+6
source share
4 answers

I often cheat.

 function createElmt(html) { var div = document.createElement('div'); div.innerHTML = html; return div.childNodes[0]; } 
+4
source

Since Tom's solution will not work if the html line consists of siblings, I would 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/

+1
source

Can I suggest the following function if you want to use it in pure javascript

  function addChild(parent,tn,attrs) { var e = document.createElement(tn); if(attrs) { for(var attr in attrs) { e.setAttribute(attr,attrs[attr]); } } parent.appendChild(e); return e; } 

Example

 var li = addChild(document.getElementById('ul tag id'),'li',{"class" : 'station_li'}); var span = addChild(li,'span',{"class" : 'seq_num'}); var a = addChild(li,'a',{ href:"javascript:void(0);" , "class":"remove_li_link"}); a.innerHTML = 'some thing' 

Respectfully:)

0
source

Use . innerHTML . It used to be not a standard, but now it is part of HTML5.

 var li = document.createElement('li'); li.className = "station_li"; li.innerHTML = '<span class="seq_num"></span>\ <a href="javascript:void(0);" class="remove_li_link">delete</a>'; 

Or, if you need to create many of them,

 var ul = document.createElement('ul'); // repeat as necessary: ul.innerHTML += '<li class="station_li">\ <span class="seq_num"></span>\ <a href="javascript:void(0);" class="remove_li_link">delete</a>\ </li>'; 

Edit: for best performance, do not add to innerHTML; create an array of strings instead:

 ul.innerHTML = arrayOfFragments.join(''); 

More info on innerHTML from MDN

0
source

Source: https://habr.com/ru/post/902540/


All Articles