getElementsByTagName() equivalent for textNodes

前端 未结 7 826
日久生厌
日久生厌 2020-11-22 06:33

Is there any way to get the collection of all textNode objects within a document?

getElementsByTagName() works great for Elements, but

7条回答
  •  不思量自难忘°
    2020-11-22 07:04

    after createTreeWalker is deprecated you can use

      /**
       * Get all text nodes under an element
       * @param {!Element} el
       * @return {Array}
       */
      function getTextNodes(el) {
        const iterator = document.createNodeIterator(el, NodeFilter.SHOW_TEXT);
        const textNodes = [];
        let currentTextNode;
        while ((currentTextNode = iterator.nextNode())) {
          textNodes.push(currentTextNode);
        }
        return textNodes;
      }
    

提交回复
热议问题