duanchanguo7603 2018-05-01 16: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 16: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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试