0
votes

I am trying to do some dynamic CSS style updates on a site and need to use PHP over JavaScript. I need to only style div tags that contain an img tag in them and ignore the rest of the div tags.

Here is what I have so far:


    $dom = new domDocument;
    $dom->loadHTML($test);
    $dom->preserveWhiteSpace = false;

    $divs = $dom->getElementsByTagName('div');
    foreach ($divs as $div) {
        $saveXML[] = $dom->saveXML($div);
        $childNotes[] = $div->getChildNodes;
    }

I am simply trying two methods here. The problem with the $saveXML option is that it gives me the whole whack of code including the encapsulating divs. I dont want that. Plus from this point now I will have to run a regex or something on the code to find if it has an img tag inside it.

The $childNodes option should have been the best I thought but the array is returned empty. It would have been nice because I could have simply tried something like


    if ($childNode->nodeType == 'img'){
      $div->setAttribute('class', $new_attributes);
    }

(I havent thought that last bit out fully but thats the general concept)..

Here is a sample of the HTML code I need to search through


    div class="image-left drop-shadow raised" style="width: 210px">
         img src="images/myimage.jpg" width="200" height="150" class="size-full" /
         p>EDIT THIS DIV's STYLE /p>
    /div>
    div class="blocktext" style="width: 150px;">
         p>DONT EDIT THIS DIVs STYLE /p>
    /div>

Any help please...

3

3 Answers

0
votes

I hope your sample html isnt the actual html ur using. Many of ur tags arent finished with open/closing "<"'s.

However, if its not then you could use:

$childNode->getElementsByTagName('img'); 

This would return if there is an image in it or not, from reading http://php.net/manual/en/domdocument.getelementsbytagname.php i got that it will return a list... I could be wrong but jus throwing the thought out there.

0
votes

You normally do that with an Xpath query:

$xp = new DOMXPath($dom)
$divsContainingImg = $xp->query('//div/img/..');
foreach ($divsContainingImg as $div)
{
    /* @var $div DOMElement */
    ...
}

This will select all img elements that are direct children of a div element and then it's parent (the div element).