更新:大多数主流浏览器现在都支持
document.querySelector("p").closest(".near.ancestor")请注意,这可以匹配选择器,而不仅仅是类
https://developer.mozilla.org/zh-
CN/docs/Web/API/Element.closest
对于不支持
closest()但拥有
matches()一个的旧版浏览器,可以构建类似于@rvighne的类匹配的选择器匹配:
function findAncestor (el, sel) { while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel))); return el;}


