jQuery的.is()方法在JS中的等价方法是什么?

11

现代浏览器中是否有等价于jQuery .is() 的纯JS方法?

我知道有querySelector方法,但我想检查节点本身,而不是找到子节点。


6
你可以在 GitHub 或这里查看 jQuery 的源代码:jQuery.fn.is - Adam Merrifield
1
我能看到它,但理解并摆脱它是另一个问题。此外,它无疑包括我不想要的旧浏览器支持。 - Petah
@PHPglue 不,我不需要节点名称。 - Petah
3
重复?https://dev59.com/WHA75IYBdhLWcg3wboYz - Felix Kling
只需使用 element.matches(strCssSelector); 即可,它在 Chrome 中可用,可能也适用于其他浏览器... - dandavis
显示剩余3条评论
5个回答

8

看起来matchesSelector是我想要的。

https://developer.mozilla.org/zh-CN/docs/Web/API/Element/matches

这里提供了Polyfill:

https://gist.github.com/jonathantneal/3062955

this.Element && function(ElementPrototype) {
    ElementPrototype.matchesSelector = ElementPrototype.matchesSelector || 
    ElementPrototype.mozMatchesSelector ||
    ElementPrototype.msMatchesSelector ||
    ElementPrototype.oMatchesSelector ||
    ElementPrototype.webkitMatchesSelector ||
    function (selector) {
        var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1;

        while (nodes[++i] && nodes[i] != node);

        return !!nodes[i];
    }
}(Element.prototype);

3

你已经回答了自己的问题,但是根据我上面的评论,我查看了jQuery.fn.is函数。这不是源代码中的剥离,因为他们使用的函数更加通用,可以在多个其他函数中使用,但我将其简化为以下函数:

function is(elem, selector){ //elem is an element, selector is an element, an array or elements, or a string selector for `document.querySelectorAll`
    if(selector.nodeType){
        return elem === selector;
    }

    var qa = (typeof(selector) === 'string' ? document.querySelectorAll(selector) : selector),
        length = qa.length,
        returnArr = [];

    while(length--){
        if(qa[length] === elem){
            return true;
        }
    }

    return false;
}

DEMO


2
另一种方法:将要测试的元素包装在父元素中,然后从该父元素运行querySelector
function is(el, selector) {
  var div = document.createElement('div');
  div.innerHTML = el.outerHTML;
  return div.querySelector(selector);
}

我进行了一项测试,它成功了:

JS

var a = document.querySelector('a');

 if(is(a, '.foo[name=foo]')) {
  console.log('YES');
} else {
  console.log('Nope');
}

HTML

<a href="#" class="foo" name="foo">Meow</a>

我相信这个可以更漂亮地完成。


0
根据youmightnotneedjquery.com,根据您的IE兼容性要求,甚至可以得到更简单的版本:
var is = function(element, selector) {
  return (element.matches || element.matchesSelector || element.msMatchesSelector || 
    element.mozMatchesSelector || element.webkitMatchesSelector || 
    element.oMatchesSelector).call(element, selector);
};

is(element, '.my-class');

使用ES6,这将是:

const is = (element, selector) =>
  (element.matches || element.matchesSelector || element.msMatchesSelector || 
    element.mozMatchesSelector || element.webkitMatchesSelector || 
    element.oMatchesSelector).call(element, selector);
};

is(element, '.my-class');

-2
根据 @AdamMerrifield 的概念,通过以下方式在任何元素上建立方法 is 可能会很有用,即通过 Element.prototype 链:
Element.prototype.is = function(match) {
    ...
};

Element被所有主要的浏览器支持,甚至包括IE 8+。

这里有一个演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接