我需要以下面的形式向DOM添加一个元素:
<div class='spelling'>Are you sure "<span class='anotherclass'>abc</span>" is a verb?</div>
我的尝试如下:
$node = $divs->item($i);
if ($node->getAttribute('class') == 'card') {
$ele=$dom->createElement('div');
$ele->textContent = 'Are you sure "<span class="anotherclass">' . $term . '</span>" is a verb? Try looking it up in our dictionary.';
$ele->setAttribute('class', 'spelling');
$node->parentNode->insertBefore($ele,$node);
$node->parentNode->removeChild($node);
$i--;
}
这确实成功添加了新的div
;但是,它无法将span
添加为元素。相反,它只是将span
添加为div
中文本的一部分。如何让PHP将span
识别为嵌套元素而不是纯文本?
答案 0 :(得分:1)
答案 1 :(得分:1)
您可以尝试将其添加为CDATA部分,如果这仍适合您吗?
$node = $divs->item($i);
if ($node->getAttribute('class') == 'card') {
$ele=$dom->createElement('div');
// append a CDATA section rather than setting the content
$ele->appendChild($ele->ownerDocument->createCDATASection('Are you sure "<span class="anotherclass">' . $term . '</span>" is a verb? Try looking it up in our dictionary.');
$ele->setAttribute('class', 'spelling');
$node->parentNode->insertBefore($ele,$node);
$node->parentNode->removeChild($node);
$i--;
}