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

时间:2019-10-24 14:48:03

标签: javascript jquery

当我遍历列表时如何获得以前的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 个答案:

答案 0 :(得分:1)

使用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>