为了账号安全,请及时绑定邮箱和手机立即绑定

遍历已找到元素的列表时如何获取先前的 h3 值?

遍历已找到元素的列表时如何获取先前的 h3 值?

UYOU 2021-12-02 16:32:04
遍历列表时如何获取之前的 h3 内容?    var statusLabel= $("ul li:contains('Status: MyStatus')");    for(i = 0; i < statusLabel.length; i++) {          // How to i get the previous h3 content of each statusLabel    }示例 html 层次结构:<a><h3>ToBeExtracted</h3>    <div class="description">    </div><ul>    <li>Status: My status</li></ul>  
查看完整描述

1 回答

?
慕田峪7331174

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>


查看完整回答
反对 回复 2021-12-02
  • 1 回答
  • 0 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信