php DOMDocument:在特定id中选择特定的classname?

时间:2011-04-03 15:19:22

标签: php domdocument

嘿伙计们, DOMDocument类的两个问题......

我是用jQuery做的:

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

我想对DOMDocument类做同样的事情!如何才能做到这一点?我该如何选择?

第二个问题是:为什么这不起作用?

$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...??

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用DOMXPath搜索DOMDocument,然后对查询结果进行迭代,以便为class属性添加必要的值(如果它尚未存在):

// 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));
}

您的“第二个问题”代码不起作用,因为没有ID为quick-reply-submit的元素 - 没有其他可能性。