我需要以以下形式向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
作为元素。相反,它只是在div
中添加span
作为文本的一部分。如何使PHP将span
识别为嵌套元素而不是纯文本?
如果这仍然适用,您可以尝试将其添加为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--;
}