How to check if element is last child without JQuery
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.
您可以在元素上使用.nextSibling属性,并查看它是否回到空(未定义等)。
You can use the node.lastChild Property
The Node.lastChild read-only property returns the last child of the node. > If its parent is an element, then the child is generally an element node, > a text node, or a comment node. It returns null if there are no child elements..
var tr = document.getElementById("row1");
var corner_td = tr.lastChild;
The error you get should be some kind of can't set property on undefined
.
You have just to check whether the next element exists:
if (typeof element.nextSibling === "undefined")
return;
链接地址: http://www.djcxy.com/p/76658.html