如何从 DOMNode 获取innerHTML
我试图用
元素替换 DOMDocument 中的所有
元素。执行此操作的最佳方法似乎是使用 getElementsByTagName 获取所有
元素,然后创建新元素来替换它们。
问题是,我看不到从被替换的元素中获取innerHTML。 nodeValue 和 textContent 都返回内部文本,但内部标签被剥离。如何从 DOMElement 获得类似于“innerHTML”的内容?
示例代码:
function convertTags($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'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 convertTags($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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你可以通过像实际节点一样对待它们来做得更好:
I think you could do better by treating them like actual nodes:
使用
DOMDocument::saveHTML()
方法,并指定要转储的节点。如果我了解您要从中提取 HTML 的示例中的哪些节点,请尝试以下操作: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:如果将坏元素的所有子节点移到好元素中,会发生什么情况?如果不使用innerHTML 类型方法就不能完成此操作吗?
我相信 saveHTML() 应该返回您应用它的节点的标记,如果这对您有帮助的话。
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.