开发者

How to grab innerHTML from DOMNode

I'm attempting to replace all <foo> elements in a DOMDocument with <bar> elements. The best way to do this seems to be to grab all the <foo> elements with getElementsByTagName and then create new elements to replace these with.

The problem is, I can't see to grab the innerHTML from the element which is being replaced. nodeValue and textContent both return the inner text, but the inner tags get stripped away. How can a I get something similar to "innerHTML" from a DOMElement?

Sample code:

function conve开发者_开发知识库rtTags($doc, $type) {

$bad_nodes = $doc->getElementsByTagName($type); 

foreach($bad_nodes as $bad_node) {
    $good_node = $doc->createElement("bar", $bad_node->nodeValue);
    $bad_node->parentNode->replaceChild($good_node, $bad_node); 
}

return $doc;
} 


I think you could do better by treating them like actual nodes:

$good_node = $doc->createElement('bar');
foreach( $bad_node->childNodes as $kid )
{
    $good_node->appendChild( $kid );
}


Use the DOMDocument::saveHTML() method, and specify the node you want to dump. If I understand which of the nodes in your example you're looking to extract the HTML from, try something like:

foreach($bad_nodes as $bad_node) {
    $good_node = $doc->createElement("bar", $bad_node->nodeValue);
    $bad_node->parentNode->replaceChild($good_node, $bad_node); 

    // Call saveHTML on the node you want to dump.
    $doc->saveHTML($bad_node);

}


What happens if you move all the child nodes of your bad element into your good element instead? Can this not be done without using an innerHTML type method?

I believe saveHTML() should return the markup of the node you apply it to, if that's any help to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜