1 回答
TA贡献1828条经验 获得超13个赞
使用 jquery,您可以直接在 jquery 对象上启动“for each”循环,如下所示:
$("ul li:contains('Status: My status')").each(function(i,li){
console.log('h3:',$(li).closest('ul').prevAll('h3:first').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>ToBeExtracted 1</h3>
<div class="description">
</div>
<ul>
<li>some padding</li>
<li>and some more ...</li>
<li>Status: My status</li>
</ul>
<h3>ToBeExtracted 2</h3>
<div class="description">
</div>
<ul>
<li>some padding</li>
<li>and some more ...</li>
<li>Status: My status</li>
<li>some padding</li>
<li>and some more ...</li>
</ul>
<h3>ToBeExtracted 3</h3>
<div class="description">A Div in between ...
</div>
<ul>
<li>and</li>
<li>Status: My status</li>
<li>some</li>
<li>more</li>
<li>padding</li>
<li>and</li>
<li>some</li>
<li>more</li>
<li>padding</li>
</ul>
您需要先“爬上”到<ul>元素,然后.prevAll('h3:first')在同一层向后看 ( ),直到遇到第一个<h3>元素。
编辑:
这是第二个更强大的 Vanilla JS 解决方案,可以处理任何文档结构。它只是查看<h3>和<li>元素的序列- 无论它们如何堆叠 - 并返回所需的命中:
var h3,res=[];
[...document.querySelectorAll('h3,li')].forEach(e=>{
if(e.nodeName=='H3') h3=e;
if(e.nodeName=='LI' &&
e.innerText.indexOf('Status: My')>-1) res.push(h3.innerText);
});
console.log(res);
<h3>ToBeExtracted 1</h3>
<div class="description">
</div>
<div>
this is a div, encasing the first UL section
<ul>
<li>some padding</li>
<li>and some more ...</li>
<li>Status: My status</li>
</ul>
end of container-div
</div>
<h3>ToBeExtracted 2</h3>
<div class="description">
</div>
<ul>
<li>some padding</li>
<li>and some more ...</li>
<li>Status: My status</li>
<li>some padding</li>
<li>and some more ...</li>
</ul>
<h3>ToBeExtracted 3</h3>
<div class="description">A Div in between ...
</div>
<ul>
<li>and</li>
<li>Status: My status</li>
<li>some</li>
<li>more</li>
<li>padding</li>
<li>and</li>
<li>some</li>
<li>more</li>
<li>padding</li>
</ul>
添加回答
举报