开发者

DOM: with PHP, how to figure out if a node is the last child of it's parent

开发者 https://www.devze.com 2022-12-27 07:14 出处:网络
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 som

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开发者_C百科 node is the last child.

Thanks!


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`
}


Since this is a PHP question, I'll leave a PHP answer (using DOM) for the posterity:

if ($node->isSameNode($node->parentNode->lastChild))
{
    //...
}

And if you're using SimpleXML, just convert your node with dom_import_simplexml().

0

精彩评论

暂无评论...
验证码 换一张
取 消