DOM 删除选定的子节点
我在聊天中有一个带有 html 的 dom 元素,其中包含一些我想删除的 html 元素,同时仍然保留一些没问题的标签。
我尝试遍历子元素所有子元素并删除那些需要删除的元素
foreach ($node->getElementsByTagName('*') as $element)
if ($element->nodeName != 'br')
$node->removeChild($element);
但这会引发“未找到错误”异常,该异常未被捕获会导致致命错误。 我该如何解决这个问题?
I have a dom element with html inside chat contains some html elements I'd like to remove, while still keeping some tags that are ok.
I try to iterate through child elements all child elements and delete those that need to be removed
foreach ($node->getElementsByTagName('*') as $element)
if ($element->nodeName != 'br')
$node->removeChild($element);
But this throws a Not Found Error exception which not being caught causes a fatal error.
How would I solve this problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用以下命令来删除节点:
Use the following instead to remove the node:
getElementsByTagName('*')
查找所有后代元素,而不是子元素。因此,您要删除的某些$element
不是$node
的子级,因此失败。我不是 100% 确定您的意图是什么,但很可能您只是想删除某些直接子级。在这种情况下,请执行以下操作:
请注意,我们进行了两次传递:一次用于标识要删除的节点,第二次用于删除。这是因为
childNodes
是一个活动列表,因此我们在删除时无法向前迭代它。 (尽管我们可以向后迭代它。)getElementsByTagName('*')
finds all descendent elements, not child elements. So some of the$element
you want to remove are not children of$node
, hence the failure.I'm not 100% sure what your intention is here, but most likely you just want to remove certain immediate children. In this case, do the following:
Note that we make two passes: one to identify the nodes to delete, and a second pass to delete. This is because
childNodes
is an active list, so we can't iterate through it forwards as we delete. (Although we could iterate through it backwards.)