更新:
如果您有一个想要执行相同操作的 DOM 元素,请编写一个小型 jQuery 插件:
(function($) {
$.fn.splitDOMStringsByTag = function( selector ) {
var resultsArray = [];
this.find( '> ' + selector).each(function() {
resultsArray.push( $(this)[0].outerHTML.replace( /[\s\n\r]+/g, ' ' ) );
});
return resultsArray;
};
})( jQuery );
这是如何工作的:
假设你有以下 DOM
<ul id="abc">
<li>One </li>
<li>Two </li>
<li>Three </li>
<li>Three
<ul>
<li>Three point five</li>
</ul>
</li>
<li>Four </li>
</ul>
然后,您将执行以下操作:
var myArray = $('#abc').splitDOMStringsByTag('li');
并得到以下输出
myArray; // console
["<li>One </li>", "<li>Two </li>", "<li>Three </li>", "<li>Three <ul> <li>Three point five</li> </ul> </li>", "<li>Four </li>"]
myArray[3] // console
"<li>Three <ul> <li>Three point five</li> </ul> </li>"
使用普通 JS 的旧答案
var ipt = "<DIV title='Run of Network' id='525000000'>Run of Network</DIV><div title='3dServer11' id='525001499'>3dServer11</div>",
dummyDiv = document.createElement("div"),
divList = [],
a = [];
dummyDiv.innerHTML = ipt;
divList = Array.prototype.slice.call(dummyDiv.getElementsByTagName("div"));
for (var i = 0; i < divList.length; i++) {
a.push(divList[i]);
}
这会给你你想要a
的
a[0] = <DIV title='Run of Network' id='525000000'>Run of Network</DIV>
a[1] = <div title='3dServer11' id='525001499'>3dServer11</div>
要获取字符串,只需使用a[0].outerHTML
a[0].outerHTML;
// Console Output
"<div title="Run of Network" id="525000000">Run of Network</div>"