How to implement “prevUntil” in Vanilla JavaScript without libraries?

前端 未结 7 1015
遇见更好的自我
遇见更好的自我 2020-12-29 11:32

I need to implement the functionality of jQuery\'s prevUntil() method in Vanilla JavaScript.

I\'ve got several

elements on the same level:
7条回答
  •  感情败类
    2020-12-29 11:57

    You could use indexOf to determine if the index of the siblings are less than the index of the target element:

    // jshint esversion: 9
    
    // get the target node
    const node = document.querySelector("div:nth-child(3)");
    
    // get the target node's index
    const node_index = node.parentNode.indexOf(node);
    
    // get the siblings of the target node
    const siblings = node => [...node.parentNode.children].filter(child => 
      child !== node
    );
    console.log(siblings);
    
    // get the prevUntil
    const class_name = "\bmy_class\b";
    const prevUntil = siblings.filter((sibling, i) =>
      i < node_index && (sibling.getAttribute("class") || "").includes(class_name)
    );
    console.log(prevUntil);
    

    Good luck.

提交回复
热议问题