The example in this article describes the JavaScript implementation of prev and next methods for obtaining adjacent sibling nodes of an element. Share it with everyone for your reference, the details are as follows:
/** * 获取相邻元素 * @param ele 参考物元素 * @param type 类型,上一个(1)or下一个(0) * @return 返回查找到的元素Dom对象,无则返回null */ function getNearEle(ele, type) { type = type == 1 ? "previousSibling" : "nextSibling"; var nearEle = ele[type]; while(nearEle) { if(nearEle.nodeType === 1) { return nearEle; } nearEle = nearEle[type]; if(!nearEle) { break; } } return null; } /** * 获取当前执行对象的上一个元素 */ function prev() { return getNearEle(this, 1); } /** * 获取当前执行对象的下一个元素 */ function next() { return getNearEle(this, 0); } // var ele = document.getElementById("xxx"); // var prevElement = prev.call(ele); // var nextElement = next.call(ele);
Readers who are interested in more content related to JavaScript node operations can check out the special topic on this site: "Summary of JavaScript operation DOM skills"
I hope this article will be helpful to everyone in JavaScript programming.