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

遍历列表时如何获取之前的 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>  


UYOU
浏览 139回答 1
1回答

慕田峪7331174

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

相关分类

JavaScript