让我们说我有一个字符串(不是HTML--来自后端,我收到的是字符串。我只是用这种方式格式化,以便更容易阅读dom树):
<ul>
<li>
<a href="link1">Link1</a>
<a href="link2>Link2</a>
</li>
<li>
<a href="link3">Link3</a>
<a href="link4>Link4</a>
</li>
</ul>
如何抓取li
个标签并按原样检索:
[
[<a href="link1">Link1</a>, <a href="link2>Link2</a>],
[<a href="link3">Link3</a>, <a href="link4>Link4</a>]
]
我假设你需要正则表达式来实现这个目标(没有jQuery)。
答案 0 :(得分:3)
将字符串换行为div并使用DOM方法访问链接。 建议不要使用RegEx解析HTML
var html = `<ul>
<li>
<a href="link1">Link1</a>
<a href="link2">Link2</a>
</li>
<li>
<a href="link3">Link3</a>
<a href="link4">Link4</a>
</li>
</ul>`;
var div = document.createElement('div');
div.innerHTML=html;
// version 1 - just get all links in the string/div
var linksCollection = div.querySelectorAll("a"); // will have some more stuff in it
// version 2 loop each LI and then each A
var lis = div.querySelectorAll("li"),liArr = [];
for (var i = 0; i < lis.length; i++) { // querySelectorAll is array-like
var links = lis[i].querySelectorAll("a"), hrefArr=[];
for (var j = 0; j < links.length; j++) {
hrefArr.push(links[i].outerHTML);
}
liArr.push(hrefArr);
}
console.log(linksCollection)
console.log(liArr)
答案 1 :(得分:-2)
尝试以下代码: -
var list = document.getElementById("list");
var li = list.querySelectorAll("li");
//console.log(li);
var result = [];
for(var i = 0; i < li.length; i++){
var temp = [];
var anchors = li[i].querySelectorAll("a");
for(var j = 0; j < anchors.length; j++){
temp.push(anchors[j].outerHTML);
}
result.push(temp);
}
console.log(result);
<ul id="list">
<li>
<a href="link1">Link1</a>
<a href="link2">Link2</a>
</li>
<li>
<a href="link3">Link3</a>
<a href="link4">Link4</a>
</li>
</ul>