How to find all Siblings of the currently selected DOM object

前端 未结 11 1327
轻奢々
轻奢々 2020-12-08 04:25

What is the perfect way to find all nextSiblings and previousSiblings in JavaScript. I tried few ways but not getting accurate solution. If any element is selected, I need t

11条回答
  •  悲&欢浪女
    2020-12-08 05:21

    Just my two cents here, I made a couple of functions to get all the previos and the next siblings of any element.

    const getPreviousAll = element => {
      const previousAllFound = [];
      const getPrevious = element => {
        if (element !== null) {
          previousAllFound.push(element);
          const previousFound = element.previousElementSibling;
          if (previousFound !== null) {
            getPrevious(previousFound);
          }
        }
      };
      getPrevious(element.previousElementSibling);
      return previousAllFound;
    };
    const getNextAll = element => {
      const target = element;
      const nextAllFound = [];
      const getAll = element => {
        if (element !== null) {
          nextAllFound.push(element);
          const nextFound = element.nextElementSibling;
          if (nextFound !== null) {
            getAll(nextFound);
          }
        }
      };
      getAll(element.nextElementSibling);
      return nextAllFound;
    };
    

    You just have to call this functions with a node that you can get by getElementById.

提交回复
热议问题