Home > Web Front-end > JS Tutorial > JavaScript implementation of prev and next methods for obtaining adjacent sibling nodes of an element_javascript skills

JavaScript implementation of prev and next methods for obtaining adjacent sibling nodes of an element_javascript skills

WBOY
Release: 2016-05-16 15:18:18
Original
2845 people have browsed it

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);

Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template