我是用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...??
感谢您的帮助!
答案 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
的元素 - 没有其他可能性。