duanchanguo7603 2018-05-01 08:18
浏览 243
已采纳

DOM-getelementsbytagname方法在DOMNode类中不存在

I readed this DOMNode document and I found there isn't getelementsbytagname method in DOMNode. But, in my code I can use getelementsbytagname method with DOMNode. Can someone explain me why?

There is my code:

$dom = new DOMDocument;
@$dom->loadHTMLFile('http://www.poemjoy.com/show-8-27-1.html');

$xpath = new DOMXpath($dom);
$articles = $xpath->query('//div[@class="poem_detail"]');

            foreach($articles as $tnode)  
            {
                $ep=$tnode->getElementsByTagName('p');
            }

The $tnode is DOMNode type variable. I didn't find getelementsbytagname method in the document I mention before.Why can I use it?

Can someone please explain to me?

  • 写回答

1条回答 默认 最新

  • douqianxun8540 2018-05-01 08:21
    关注

    From the documentation you linked to in your question:

    For clarification:

    The assumingly 'discoverd' by previous posters and seemingly undocumented methods (.getElementsByTagName and .getAttribute) on this class (DOMNode) are in fact methods of the class DOMElement, which inherits from DOMNode.

    See: http://www.php.net/manual/en/class.domelement.php

    i.e. $tnode is a DOMElement and not just a DOMNode.

    The specification of the DOM standard (which PHP implements) describes the permitted node types in a DOM document. These are:

    Document, DocumentType, DocumentFragment, Element, Text, ProcessingInstruction, and Comment

    Source

    It also notes that these elements are simply called nodes meaning that, strictly speaking, there is really no such thing as a DOMNode but rather the DOMNode is a general term used to talk about any one of those node types.

    In your particular case (and as shown in the standard) getElementsByTagName is only a member of Element and Document.

    Since your selector is to select div elements you are actually getting a NodeList of DOMElement objects and not DOMNode objects and you can use getElementsByTagName. However this is dangerous because there is no guarantee that all your results will be DOMElement objects, therefore it's good to typecheck before you use the function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 爱快路由器端口更改错误导致无法访问
  • ¥20 安装catkin时遇到了如下问题请问该如何解决呢
  • ¥15 VAE模型如何输出结果
  • ¥15 编译python程序为pyd文件报错:{"source code string cannot contain null bytes"
  • ¥20 关于#r语言#的问题:广义加行模型拟合曲线后如何求拐点
  • ¥15 fluent设置了自动保存后,会有几个时间点不保存
  • ¥20 激光照射到四象线探测器,通过液晶屏显示X、Y值
  • ¥50 数据库开发问题求解答
  • ¥15 安装anaconda时报错
  • ¥15 小程序有个导出到插件方式,我是在分包下引入的插件,这个export的路径对吗,我看官方文档上写的是相对路径
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部