Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if element is last child without JQuery

Tags:

javascript

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.

like image 478
Joe Hansen Avatar asked Apr 13 '15 17:04

Joe Hansen


People also ask

Is last child 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.

How do you check if an element has a child?

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.

How do you check if an HTML element has a child?

HTML DOM Element hasChildNodes() The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.

How do I check if a div has a child element?

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.


2 Answers

You can use the .nextSibling property on the element and see if it comes back as empty (undefined, etc).

like image 144
El Guapo Avatar answered Oct 03 '22 07:10

El Guapo


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.

like image 22
Art3mix Avatar answered Oct 03 '22 07:10

Art3mix