1

我有这个 HTML:

<div class="hello top">some content</div>
<div class="hello top">some content</div>
<div class="hello">some content</div>
<div class="hello">some content</div>
<div class="hello">some content</div>

...而且我试图只获取那些具有“hello”类但没有“top”类的 DIV(我只想要 3 个最后的 DIV)。

我尝试了这样的事情但没有成功:

foreach( $html->find('div[class="hello"], div[class!="top"]') as $element ) {
  // some code...
}
4

4 回答 4

2

使用此方法:

var result = $("div:not(.top)");
console.log(result);

//你只会得到那些包含类“hello”的DIV。

于 2013-09-26T06:56:29.767 回答
0

这样您就可以选择 3 个最新的“hello”类名称。

<html>
    <header>
    </header>
    <body>
        <?php
        $html= '
        <div class="hello top">some content</div>
        <div class="hello top">some content</div>
        <div class="hello">ee some content</div>
        <div class="hello">ee some content</div>
        <div class="hello">ee some content</div>';

            $dom = new DomDocument();
            $dom->loadHTML($html);
            $dom_xpath = new DOMXpath($dom);
            $elements = $dom_xpath->query('//div[@class="hello"]');

            foreach($elements as $data){
               echo $data->getAttribute('class').'<br />';
            }
        ?>
    </body>
</html>
于 2013-09-26T06:48:06.470 回答
0

根据此表(在属性选择器中支持这些运算符):

Filter                Description
[attribute]           Matches elements that have the specified attribute.
[!attribute]          Matches elements that don't have the specified attribute.
[attribute=value]     Matches elements that have the specified attribute with a certain value.
[attribute!=value]    Matches elements that don't have the specified attribute with a certain value.
[attribute^=value]    Matches elements that have the specified attribute and it starts with a certain value.
[attribute$=value]    Matches elements that have the specified attribute and it ends with a certain value.
[attribute*=value]    Matches elements that have the specified attribute and it contains a certain value.

您可以使用:

foreach( $html->find('div[class$="hello"]') as $element ) {
  // some code...
}

但这不是可靠的解决方案,因为它也匹配:

<div class="top hello">
于 2013-09-26T06:45:17.473 回答
0

[attribute$=value] 匹配具有指定属性并以特定值结尾的元素。在你的情况下使用

foreach( $html->find('div[class$="hello"]') as $element ) {
  // some code...
}
于 2015-06-17T05:29:20.773 回答