简体   繁体   中英

Vanilla JS: Find all the DOM elements that just contain text

I want to get all the DOM elements in an HTML that doesn't contain any node, but text only.

I've got this code right now:

var elements = document.querySelectorAll("body *");
for(var i = 0; i < elements.length; i++) {
    if(!elements[i].hasChildNodes()) {
        console.log(elements[i])
    }
}

This prints of course elements that have absolutely no content (and curiously enough, iframes). Texts are accounted as a child node, so the .childNodes.length equals 1, but I don't know how to distinguish the nodes from the text. typeof the first node is always object, sadly.

How to distinguish the texts from the nodes?

You can check for elements that have no .firstElementChild , which means it will only have text (or other invisible stuff).

 var elements = document.querySelectorAll("body *"); for (var i = 0; i < elements.length; i++) { if (!elements[i].firstElementChild) { console.log(elements[i].nodeName) } } 
 <p> text and elements <span>text only</span> </p> <div>text only</div> 

The script that the stack snippet is included because it also only has text. You can filter out scripts if needed. This will also include elements that can not have content, like <input> .

Basically you are looking for leaf nodes of DOM with something inside the textContent property of the leaf node.

Let's traverse DOM and work out our little logic on leaf nodes.

const nodeQueue = [ document.querySelector('html') ];    
const textOnlyNodes = [];
const textRegEx = /\w+/gi;

function traverseDOM () {
  let currentNode = nodeQueue.shift();

  // Our Leaf node
  if (!currentNode.childElementCount && textRegEx.test(currentNode.textContent)) {
    textOnlyNodes.push(currentNode);
    return;
  }

  // Nodes with child nodes
  nodeQueue.push(...currentNode.children);
  traverseDOM();
}

childElementCount property make sure that the node is the leaf node and the RegEx test on textContent property is just my understanding of what a text implies in general. You can anytime tune the expression to make it a btter fit for your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM