Search code examples
phpsimple-html-dom

Simple-HTML-DOM: looking for a hasClass() method (or list of classes)?


I have a list of divs with different classes. Let's say:

<div class="a">A</div>
<div class="a b">A&B</div>
<div class="a">A</div>

I get these divs by $res = $DOM->find('div.a') How can I determine, if a div also has the other class b?

Like if ($res->hasClass('b')) { /*do ...*/ }

I also noticed there are the methods hasAttribute() and getAttribute(), but they don't quite help me as I need to check for a class, which is an attribute itself.

Note: I don't want to select directly via class b.

Reference: https://simplehtmldom.sourceforge.io/manual_api.htm


Solution

  • You can retrieve HTML element attributes using getAttribute() method, and class is one of those attributes. The method will return the string value of the attribute, so you need to check for other classes manually. Of course, you can easily extend simple_html_dom class and add a hasClass method:

    $src =<<<src
    <div class="a">A</div>                                                                                                                                                   
    <div class="a b">A&B</div>
    <div class="a">A</div>
    src;
    
    $html = str_get_html($src);
    
    foreach($html->find('.a') as $a) 
    {
        // put all element classes in an array
        $classes = explode(' ', $a->getAttribute('class'));
        print $a . " has following css classes: ";
        print_r($classes);
    }