如果元素是连续的,如何从DOM中删除元素

时间:2019-07-10 14:06:52

标签: php html dom xpath

我继承了以下PHP代码,该代码在将内容推送到页面之前从DOM中删除了元素。我们只想显示前5个元素的页面没有太长

假设代码检索了如下结构的HTML片段:

<div class='year'>2019</div>
<div class='record'>Record A</div>
<div class='record'>Record B</div>
<div class='year'>2018</div>
<div class='record'>Record C</div>
<div class='record'>Record D</div>
<div class='record'>Record E</div>
<div class='year'>2017</div>
<div class='record'>Record F</div>
<div class='year'>2016</div>
<div class='record'>Record G</div>

现在,以下代码删除了所有多余的records

$dom = new DOMDocument();
// be sure to load the encoding
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $tmp);
// let's use XPath
$finder = new DomXPath($dom);
// set the limit
$limit = 5; $cnt = 0;
// and remove unwanted elements
foreach($finder->query("//*[contains(@class, 'record')]") as $elm ) {
    if ($cnt >= $limit)
        $elm->parentNode->removeChild($elm);
        $cnt++;
    }
// finally, echo
echo $dom->saveHTML($dom->documentElement);

从逻辑上讲,我最终拥有以下HTML:

<div class='year'>2019</div>
<div class='record'>Record A</div>
<div class='record'>Record B</div>
<div class='year'>2018</div>
<div class='record'>Record C</div>
<div class='record'>Record D</div>
<div class='record'>Record E</div>
<div class='year'>2017</div>
<div class='year'>2016</div>

我如何确定所有具有类year并具有下一个同级也具有该类的元素并将其删除? (这里将获得2017年元素)

那么我相信这只是检查最后一个元素是否具有类year并将其删除。

还是有一种更清洁的方法来实现这一目标?

3 个答案:

答案 0 :(得分:1)

您可以在当前位置之后添加一个额外的foreach ...

foreach($finder->query("//div[@class='year']/following-sibling::div[1][@class='year']") 
        as $elm ) {
    $elm->parentNode->removeChild($elm);
}

这里的XPath在寻找一个<div class="year">元素,然后只为同一件事寻找下一个<div>标签(following-sibling::div[1]将其限制为当前元素之后的下一个div标签。一个)。

答案 1 :(得分:0)

如果您想在客户端上执行此操作,则这里是普通的JS方法

const recs = document.querySelectorAll(".record");
const divs = document.querySelectorAll("div");
const lastRec = recs[4];
let found = false;
divs.forEach(div => {
  div.classList.toggle("hide",found)
  if (div === lastRec) found = true
})
.hide { display:none}
<div class='year'>2019</div>
<div class='record'>Record A</div>
<div class='record'>Record B</div>
<div class='year'>2018</div>
<div class='record'>Record C</div>
<div class='record'>Record D</div>
<div class='record'>Record E</div>
<div class='year'>2017</div>
<div class='record'>Record F</div>
<div class='year'>2016</div>
<div class='record'>Record G</div>

答案 2 :(得分:0)

我最终使用了以下代码:

fan/10
55

它使我可以在不使用嵌套循环的情况下一口气实现目标