1

I need to add an element to my DOM in the following form:

<div class='spelling'>Are you sure "<span class='anotherclass'>abc</span>" is a verb?</div>

My attempt is as follows:

$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--;
}

This does successfully add the new div; however, it fails to add the span as an element. Instead, it just adds the span as a part of the text within the div. How do I make PHP recognize the span as a nested element and not plain text?

TheLearner
  • 2,813
  • 5
  • 46
  • 94

1 Answers1

1

You could try adding it as a CDATA section, if that would still work for you?

$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--;
}
benJ
  • 2,442
  • 1
  • 18
  • 16