JavaScript encapsulation function: get the next / previous sibling node

Time:2021-1-11

requirement:

  1. Get the next / previous sibling element node, excluding the text node, etc
  2. Solve ie compatibility problem

Code implementation:

Get the next sibling element node:

function getNextElement(element) {
    var el = element;
    while (el = el.nextSibling) {
        if (el.nodeType === 1) {
            return el;
        }
    }
    return null;
}

Get the last sibling element node:

function getPrevElement(element) {
    var el = element;
    while (el = el.previousSibling) {
        if (el.nodeType === 1) {
            return el;
        }
    }
    return null;
}

Implementation effect:

There are two labels:

div
span

Get the next sibling element node:
Input:

var div = document.querySelector('div');
console.log(getNextElement(div));

Output:

span

Get the last sibling element node:
Input:

var span = document.querySelector('span');
console.log(getPrevElement(span));

Output:

div