0

hey guys, two questions to the DOMDocument class...

I'm doing this with jQuery:

$('#wpf-wrapper .wpf-table .wpf-input').addClass('input-field');

I wanna do the same with the DOMDocument Class! How can this be done? How can I select this?

Second question is: Why is that not working?

$dom = new SmartDOMDocument();
$dom->loadHTML($shortcode);
$xpath = new DOMXPath($dom);

$qr = $dom->getElementById('quick-reply-submit');
//$qr->setAttribute('class', 'btn small width480');
//ERROR: Call to a member function on a non-object...??

Thank you for your help!

matt
  • 42,713
  • 103
  • 264
  • 397
  • it's a very usefull class that extends the DOMDocument class to have better UTF-8 support, etc. – matt Apr 03 '11 at 16:26
  • care to provide an answer with a link to that lib in [Best Methods to parse HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662)? Can't hurt to have it there. – Gordon Apr 03 '11 at 17:10

1 Answers1

1

You can use DOMXPath to search your DOMDocument, and then iterate over the query results to add the necessary value to the class attribute if it's not already there:

// This is the equivalent of '#wpf-wrapper .wpf-table .wpf-input'
$expr = '//*[@id="wpf-wrapper"]//*[@class="wpf-table"]//*[@class="wpf-input"]';

$result = $xpath->query($expr);
for($i = 0; $i < $result->length; ++$i) {
    // Get the classes of each matched element
    $classes = explode(' ', $result->item($i)->getAttribute('class'));

    // Add "input-field" if it's not in there already
    if(!in_array('input-field', $classes)) {
        $classes[] = 'input-field';
    }

    // Set the class attribute to the new value
    $result->item($i)->setAttribute('class', implode(' ', $classes));
}

Your "second question" code doesn't work because there is no element with an id of quick-reply-submit -- there is no other possibility.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • thank you... one last question. How can I select a tagname within a series of selectors like...e.g. `$expr = '//*[@id="wpf-wrapper"]//*[@class="wpf-table"]//*[@tagname="a"]';` So I'd like to select all anchors inside of wpf-table? – matt Apr 03 '11 at 16:30
  • @mathiregister: That one is `//*[@class="wpf-table"]//a`. Take a look at an XPath syntax tutorial for more, there are lots and lots of possibilities. There is one here: http://zvon.org/xxl/XPathTutorial/General/examples.html – Jon Apr 03 '11 at 16:39