要求是保持标题 - head1和head2以及在head1和head2 id之后出现的第一个div元素,并删除所有其他的heading和div元素。 请查看预期的输出可以让您清楚了解我的要求。
输入HTML:
Elements contElements = document.select("main-content");
for(Element e : contElements) {
if(e.tagName().equals("h1") && (!e.attr("id").equals("head1") && !e.attr("id").equals("head2")){
//remove h1 element with other id and all div's after this h1 element
document.select("h1 ~ div ");
e.remove();
}
else {
//keep h1 element and the first div comes after h1 and remove all other divs comes after this h1
document.select("h1 ~ div");
}
以下是我的代码:
<html>
<head> </head>
<body>
<div ID="main-content">
<div class="abc"> sample data </div>
<h1 id="head1">Example 1</h1>
<div class="abc">
<table> <tr><td> table data</td></tr></table>
</div>
<h1 id="head2">Example 2 </h1>
<div class="abc">
<table> <tr><td> table data</td></tr></table>
</div>
</div>
</body>
</html>
但上面的代码段没有按预期工作。还有什么可以实现预期的输出。
我的预期输出:
$scope.results = [
{ id: 1, name: 'tom', job: 'doctor' },
{ id: 2, name: 'bob', job: 'dentist' },
{ id: 3, name: 'steve', job: 'teacher' }
答案 0 :(得分:1)
您可以使用css选择器而不是显式循环。
选择并移除h1
不是id
且而非#head1
的所有#head2
元素:
document.select("#main-content h1:not(#head1):not(#head2)").remove();
选择并删除所有div
元素,这些元素不会立即以h1
开头:
document.select("#main-content div:not(h1 + div)").remove();
如果您只想对#main-content
的直系后代进行操作,请将>
放在其后面。