Is it possible to make querySelectorAll live like getElementsByTagName?

前端 未结 2 764
死守一世寂寞
死守一世寂寞 2021-02-07 12:59

getElementsByTagName() has 2 great features: it is fast and it is live. But what if I want to get p strong. Of course I could refine a selection using

2条回答
  •  被撕碎了的回忆
    2021-02-07 13:53

    Consider using mutation observers. Watch for childList with subtree: true. When the notification arrives, you can examine each added node with matches to see if it matches some selector.

    function querySelectorAllLive(element, selector) {
    
      // Initialize results with current nodes.
      var result = Array.prototype.slice.call(element.querySelectorAll(selector));
    
      // Create observer instance.
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          [].forEach.call(mutation.addedNodes, function(node) {
            if (node.nodeType === Node.ELEMENT_NODE && node.matches(selector)) {
              result.push(node);
            }
          });
        });
      });
    
      // Set up observer.
      observer.observe(element, { childList: true, subtree: true });
    
      return result;
    }
    

提交回复
热议问题