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
I often cheat.
function createElmt(html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.childNodes[0];
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With