[removed] How to get parent element by selector?

前端 未结 9 483
忘掉有多难
忘掉有多难 2020-12-02 16:31

Example:

....
<
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 17:04

    simple example of a function parent_by_selector which return a parent or null (no selector matches):

    function parent_by_selector(node, selector, stop_selector = 'body') {
      var parent = node.parentNode;
      while (true) {
        if (parent.matches(stop_selector)) break;
        if (parent.matches(selector)) break;
        parent = parent.parentNode; // get upper parent and check again
      }
      if (parent.matches(stop_selector)) parent = null; // when parent is a tag 'body' -> parent not found
      return parent;
    };
    

提交回复
热议问题