Manny
Manny

Reputation: 566

How to get DIVs with certain class and also without?

I've got this 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>

... and i am trying to get only those DIVs which has class "hello" but not class "top" (i want 3 last DIVs only to get).

I tried something like this but without success:

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

Upvotes: 1

Views: 841

Answers (4)

jhenya-d
jhenya-d

Reputation: 399

[attribute$=value] Matches elements that have the specified attribute and it ends with a certain value. in your case use

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

Upvotes: 0

Tarun Singhal
Tarun Singhal

Reputation: 1007

Use this method:

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

//You will get only those DIV which contains class "hello".

Upvotes: 2

Duikboot
Duikboot

Reputation: 1101

This way you can select already your 3 latest "hello" class names.

<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>

Upvotes: 0

Jason OOO
Jason OOO

Reputation: 3552

According to this table ( Supports these operators in attribute selectors):

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.

You can use:

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

But this is not reliable solution because it matches also:

<div class="top hello">

Upvotes: 0

Related Questions