php dom add class to element 1

php dom add class to element

$dom = new DOMDocument;
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
        $div->setAttribute('class', $div->getAttribute('class').' myclass');
}
$html = $dom->saveHTML();

Here is what the above code is Doing:
1. Load the HTML into a DOMDocument object.
2. Get all the divs in the document.
3. Loop through the divs and add the class myclass to each div.
4. Save the HTML back to a string.

Similar Posts