dotj78335 2010-04-16 11:03
浏览 23
已采纳

DOM:使用PHP,如何确定节点是否是其父节点的最后一个子节点

I'm trying to figure out how to know if a node is the last child of another, or not.

I know how to retrieve the parent's lastChild name ($node->parentNode->lastChild->nodeName), but as sometimes there's many same node names within the same parent, the name is definitly not the way to find the last child.

I'm looking for some kind of iterator which can retrieve the number of childs, and depending of the position of the current node, tell if the current node is the last child.

Thanks!

  • 写回答

2条回答 默认 最新

  • dongyikong6207 2010-04-16 11:08
    关注

    In pure DOM terms, if the child is the last child of a parent, its nextSibling property will be null.

    Javascript example (not that you're looking for Javascript specifically):

    if (!child.nextSibling) {
        // It's the last child
    }
    

    It's important to note that nextSibling traverses nodes. Sometimes you want to traverse elements instead (as opposed to text nodes and such). For instance, in this markup:

    <p>Testing <span>one</span> two three</p>
    

    ...the span is not the last node in its container (because it's followed by a text node), but it is the last element in its container. If you want to look for that, you need a loop checking the nodeType, e.g.:

    // =====
    // Note: This example is in JavaScript, but I assume it's easy enough
    // to follow what it's doing and translate it to PHP
    // =====
    
    // Utility function
    function nextElement(node) {
        var rv = node.nextSibling;
        while (rv && rv.nodeType !== 1) {
            rv = rv.nextSibling;
        }
        return rv;
    }
    
    // Usage
    if (!nextElement(child)) {
        // There was no element after `child`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!