Bacon Bacon - 1 year ago 72
PHP Question

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

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

name (
), 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.


Answer Source

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`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download