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