[英]JQuery: How to extract li items from div
I have the following div that contain an unordered list and other code:我有以下包含无序列表和其他代码的 div:
<div id="myDiv">
<ul>
<div id="myInnerDiv">Here is a div</div>
<li id="oneLi">One li</li>
<script type="text/javascript">
// some JS code
</script>
<li><span class="li-item">Some content 1</span></li>
<li><span class="li-item">Some content 2</span></li>
<li><span class="li-item">Some content 3</span></li>
</ul>
</div>
I want to get the HTML corresponding to the latest <li>
items after the <script>
tag:我想在
<script>
标签之后获取与最新的<li>
项对应的 HTML:
<ul>
<li><span class="li-item">Some content 1</span></li>
<li><span class="li-item">Some content 2</span></li>
<li><span class="li-item">Some content 3</span></li>
</ul>
or just the li item:或只是 li 项目:
<li><span class="li-item">Some content 1</span></li>
<li><span class="li-item">Some content 2</span></li>
<li><span class="li-item">Some content 3</span></li>
Do you know how to reach that with jQuery?你知道如何用 jQuery 达到这个目标吗?
You can select the elements after another element by using the Next Siblings Selector (~)
您可以使用
Next Siblings Selector (~)
在另一个元素之后选择元素
You can also use .nextAll()
to achieve the same - $('#myDiv script').nextAll('li')
您也可以使用
.nextAll()
来实现相同的 - $('#myDiv script').nextAll('li')
I've also used .clone()
to safely use .wrapAll('<ul>')
on the returned element without effecting the DOM我还使用
.clone()
在返回的元素上安全地使用.wrapAll('<ul>')
而不会影响 DOM
// Returns a jQuery object containing the three <li> items after script // Then clone ( to leave DOM as is ) and wrap with <ul> const $listElements = $('#myDiv script ~ li').clone().wrapAll('<ul>'); // Get HTML of <ul> const listHTML = $listElements.parent().prop('outerHTML'); console.log(listHTML); // Get HTML of just <li> const itemHTML = $listElements.parent().html(); console.log(itemHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="myDiv"> <ul> <div id=" myInnerDiv ">Here is a div</div> <li id="oneLi ">One li</li> <script type="text/javascript "> // some JS code </script> <li><span class="li-item ">Some content 1</span></li> <li><span class="li-item ">Some content 2</span></li> <li><span class="li-item ">Some content 3</span></li> </ul> </div>
假设您想要最新列表项的内容:
$("#myDiv ul li:last").text()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.