Test if a selector matches a given element

后端 未结 7 1657
庸人自扰
庸人自扰 2020-11-27 05:58

Is there any way to test if a selector would match a given DOM Element? Preferably, without the use of an external library like Sizzle. This is for a library and I would li

7条回答
  •  清歌不尽
    2020-11-27 06:39

    In the absence of xMatchesSelector, I'm thinking to try adding a style with the requested selector to a styleSheet object, along with some arbitrary rule and value that is not likely to be already in use. Then check the computed/currentStyle of the element to see if it has inherited the added CSS rule. Something like this for IE:

    function ieMatchesSelector(selector, element) {
      var styleSheet = document.styleSheets[document.styleSheets.length-1];
    
      //arbitrary value, probably should first check 
      //on the off chance that it is already in use
      var expected = 91929;
    
      styleSheet.addRule(selector, 'z-index: '+expected+' !important;', -1);
    
      var result = element.currentStyle.zIndex == expected;
    
      styleSheet.removeRule(styleSheet.rules.length-1);
    
      return result;
    }
    

    There's probably a handbag full of gotcha's with this method. Probably best to find some obscure proprietary CSS rule that is less likely to have a visual effect than z-index, but since it is removed almost immediately after it is set, a brief flicker should be the only side effect if that. Also a more obscure rule will be less likely to be overridden by a more specific selector, style attribute rules, or other !important rules (if IE even supports that). Anyway, worth a try at least.

提交回复
热议问题