I have a pure Javascript script with an onclick event that checks the value of the next sibling before deciding what to do. This will cause an error if the element clicked is the last element in its container (because of accessing nextSibling). I need to first check that the element clicked is not the last element in the container, but can't seem to find out how.
Note: I don't think this is a duplicate. There are quite a few questions about checking if an element is the last child, but all accepted answers—all answers in general—use JQuery.
Definition and UsageThe :last-child selector selects all elements that are the last child of their parent. Tip: Use the :first-child selector to select elements that are the first child of their parent.
Use one of the firstChild, childNodes. length, children. length property to find whether element has child or not. hasChildNodes() method can also be used to find the child of the parent node.
HTML DOM Element hasChildNodes() The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.
Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.
You can use the .nextSibling property on the element and see if it comes back as empty (undefined, etc).
For some reason none of the answers worked for me, I always ended up seeing a #text
node instead of undefined or null, so I ended up comparing my element with the last child of the parent of the element:
element === element.parentNode.children[element.parentNode.children.length-1]
or if you want it as a function
function isLastChild(el) {
return (el === el.parentNode.children[el.parentNode.children.length-1])
}
//Useage
if(isLastChild(el)) {
//Element is the last child of its parent.
}
Might be longer than other answers but surly won't fail you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With