jQuery -在一些标签之间获取所有html

jQuery - Get all html in between some tags

本文关键字:获取 html 之间 标签 jQuery      更新时间:2023-09-26

我需要刮一个网站,看起来像这样:

<p></p>
<!-- I want to get HTML from here... -->
<h2> </h2>
<table> </table>
<h2> </h2>
<table> </table>
<h2> </h2>
<table> </table>
<!-- to here -->
<div> </div>
<h2> </h2>
<table> </table>

如上所述,我想获得<p><div>之间的所有HTML。我不希望<h2><table>在div下面。

有没有好办法刮掉这些零件?如果可能的话,我希望避免以子索引为目标。

谢谢

$('p').nextUntil('div').addClass('add')
.add{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<!-- I want to get HTML from here... -->
<h2> I want to get HTML from here...</h2>
<table><tr><td>I want to get HTML from here...</td></tr> </table>
<h2> I want to get HTML from here...</h2>
<table><tr><td>I want to get HTML from here...</td></tr> </table>
<h2> I want to get HTML from here...</h2>
<table><tr><td>I want to get HTML from here...</td></tr> </table>
<!-- to here -->
<div> </div>
<h2> </h2>
<table> </table>

使用.nextUntil ()

获取每个元素的所有兄弟元素,但不包括与选择器、DOM节点或传递的jQuery对象匹配的元素。

使用.nextUntil()获取从特定元素到任何特定元素的所有next元素。

console.log($("p:first").nextUntil("div"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p></p>
<!-- I want to get HTML from here... -->
<h2> </h2>
<table> </table>
<h2> </h2>
<table> </table>
<h2> </h2>
<table> </table>
<!-- to here -->
<div> </div>
<h2> </h2>
<table> </table>