[removed] How to get parent element by selector?

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

Example:

....
<
9条回答
  •  眼角桃花
    2020-12-02 17:13

    Finds the closest parent (or the element itself) that matches the given selector. Also included is a selector to stop searching, in case you know a common ancestor that you should stop searching at.

    function closest(el, selector, stopSelector) {
      var retval = null;
      while (el) {
        if (el.matches(selector)) {
          retval = el;
          break
        } else if (stopSelector && el.matches(stopSelector)) {
          break
        }
        el = el.parentElement;
      }
      return retval;
    }
    

提交回复
热议问题