Search code examples
phpforeachsimple-html-dom

Find DIV with multiple classes and id


I am using Simple HTML DOM and I am trying to get a certain element which holds both an ID and a set of classes like this:

<div id="leadtxt" class="caption"></div>

foreach($html->find('div #leadtxt .caption', 0) as $element) 
       echo $element->outertext;

According to the documentation this should get me the div that has id #leadtxt and also has class .caption The problem is that it doesn't. How should I write this?


Solution

  • Your code will try to find an element with the class of caption within the element with the ID of leadtxt. Since you have an ID, and IDs must be unique, it would make more sense to simply use that:

    $html->find('#leadtxt', 0)
    

    The exact answer to your question would be this:

    $html->find('div#leadtxt.caption', 0)
    

    Note the lack of space - it'll find the div element with the ID of leadtxt and the class of caption. But again, this is redundant and the above approach would be better and most likely faster.

    Edit: here are some further examples as I'm not clear on exactly what you are trying to do.

    The following would find all elements which have the ID of leadtxt or the class of caption:

    $html->find('#leadtxt, .caption')
    // OR specify the fact you only want DIV elements...
    $html->find('div#leadtxt, div.caption')
    

    This would specify you want elements with ANY of the given classes (one or more):

    $html->find('.classone, .classtwo, .classthree')
    // OR just the DIV elements with any of these classes:
    $html->find('div.classone, div.classtwo, div.classthree')
    

    This would specify any elements with ALL the given classes:

    $html->find('.classone.classtwo.classthree')
    // OR again, just DIV elements...
    $html->find('div.classone.classtwo.classthree')
    

    Edit 2: as you have already said, it seems Simple HTML DOM fails whenever you provide a selector which specifies multiple classes/IDs together. I can only assume that is a weakness in the library which has not yet been addressed. Its a shame, as it means it does not work with the standard CSS selectors given above, despite claiming to.