最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to make querySelectorAll live like getElementsByTagName? - Stack Overflow

programmeradmin7浏览0评论

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 getElementsByTagName() again but wouldn't I lose the live effect for the new p tags?

Is there a way to turn querySelectorAll into a live selector?

Or... is there a way to use getElementsByTagName() and getElementsByClassName() to create a function that works in a similar way (at least with descendants) as querySelectorAll but being live?

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 getElementsByTagName() again but wouldn't I lose the live effect for the new p tags?

Is there a way to turn querySelectorAll into a live selector?

Or... is there a way to use getElementsByTagName() and getElementsByClassName() to create a function that works in a similar way (at least with descendants) as querySelectorAll but being live?

Share Improve this question edited Sep 9, 2016 at 4:26 user663031 asked Jun 1, 2015 at 16:35 VandervalsVandervals 6,0547 gold badges53 silver badges101 bronze badges 1
  • 3 Such a feature, if implemented natively, would probably be excluded from the dynamic profile, preventing level 4 selectors like :has() with complex selectors from being used, as live selector matching is basically what happens in CSS and as such is performance-sensitive. Still, I'm curious to know. – BoltClock Commented Jun 1, 2015 at 16:42
Add a comment  | 

2 Answers 2

Reset to default 13

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;
}

I don't think it is possible because subsequent changes of the DOM does not reflect in the NodeList object returned by the querySelectorAll() method.

Selectors-api W3C

发布评论

评论列表(0)

  1. 暂无评论