如何将html字符串拆分为DOM元素?
问题描述:
我有一个html字符串
I have a html string
var str = '<span class="linq" onclick="ShowData(2,-1,1);">11111</span> » <span class="linq" onclick="ShowData(16,1,1);">22222</span> » 33333';
我需要将其拆分为数组。
I need to split it to an array.
arr[0] = "<span class="linq" onclick="ShowData(2,-1,1);">11111</span>";
arr[1] = " » "
arr[2] = "<span class="linq" onclick="ShowData(16,1,1);">22222</span>";
arr[3] = " » 33333'"
我尝试使用$ .parseHTML(),但我使用的是jquery 1.6,现在无法升级。
如果我使用$(str)我得到一个数组但没有最后一项。
I tried to use $.parseHTML() but i'm using jquery 1.6 and can't upgrade for now. If i use $(str) i get an array but without the last item.
arr[0] = "<span class="linq" onclick="ShowData(2,-1,1);">11111</span>";
arr[1] = " » "
arr[2] = "<span class="linq" onclick="ShowData(16,1,1);">22222</span>";
答
这是一种方法:
var temp = document.createElement('div');
temp.innerHTML = str;
var arr = Array.prototype.map.call(temp.childNodes, function(node) {
return node.nodeType === 1
? node.outerHTML
: node.nodeValue;
});