How to find all Siblings of the currently selected DOM object

前端 未结 11 1326
轻奢々
轻奢々 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:06

    A simple solution using ES2015 (spread & indexOf)

    const getSiblings = (elm, withTextNodes) => {
      if( !elm || !elm.parentNode ) return
      
      let siblings = [...elm.parentNode[withTextNodes ? 'childNodes' : 'children']],
          idx = siblings.indexOf(elm);
      
      siblings.previous = siblings.slice(0, idx)
      siblings.next = siblings.slice(idx + 1)
      
      return siblings
    }
    
    // Usage example:
    const testElm = document.querySelector('em');
    const testElmSiblings = getSiblings(testElm);
    
    console.log(
      testElmSiblings.previous,
      testElmSiblings.next,
      testElmSiblings
    )
    text node 1

    text node 2

提交回复
热议问题