close

.closest()
Element.closest()方法用來獲取:匹配特定選擇器且離當前元素最近的祖先元素(也可以是當前元素本身)。如果匹配不到,則返回null。

var elem = document.querySelector('#some-element');
var closestParent = elem.closest('.pick-me');

.closest()瀏覽器支援度不夠好,但有polyfill可以支援至IE9+

if (window.Element && !Element.prototype.closest) {
Element.prototype.closest =
function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i,
el = this;
do {
i = matches.length;
while (--i >= 0 && matches.item(i) !== el) {};
} while ((i < 0) && (el = el.parentElement));
return el;
};
}

arrow
arrow
    文章標籤
    .closest()
    全站熱搜
    創作者介紹
    創作者 浣熊 的頭像
    浣熊

    前端生涯

    浣熊 發表在 痞客邦 留言(0) 人氣()