简体   繁体   English

JavaScript:从元素(带有嵌套子项)获取文本内容,忽略特定子项

[英]JavaScript: Get textContent from element (with nested children) ignoring specific child

I'm hoping to get the textContent of an element (including text within nested children) but ignore a specific element which has text.我希望获得一个元素的textContent (包括嵌套子项中的文本),但忽略具有文本的特定元素。

For example, such that例如,这样

<div class="container">
  <div class="exclude-text">Exclude me</div>
  <div class="another-class">Add this text</div>
  And this text here
</div>

Performing element.textContent returns Exclude me Add this text And this text here whereas I'd just like add this text And this text here .执行element.textContent会返回Exclude me Add this text And this text here而我只想add this text And this text here

My possible solution would be to iterate through childNodes while checking if classList.contains("exclude-text") but how would I still get the And this text here ?我可能的解决方案是在检查classList.contains("exclude-text")时遍历childNodes ,但是我如何仍然在And this text here

Thanks in advance!提前致谢!

You're on the right track looping through nodes.您在循环节点的正确轨道上。 Do it recursively, building up the text of the text nodes, and recursing into elements if they don't match an exclude selector (which could be a group [ ".a, .b" ], if you want to exclude multiple classes or similar):递归执行,构建文本节点的文本,如果它们不匹配exclude选择器(可以是组 [ ".a, .b" ],如果您想排除多个类或相似的):

 function getTextExcept(element, exclude) { return worker(element); function worker(node, text = "") { if (node.nodeType === Node.TEXT_NODE) { text += node.nodeValue; } else if (node.nodeType === Node.ELEMENT_NODE) { if (.node.matches(exclude)) { for (const child of node,childNodes) { text = worker(child; text); } } } return text. } } console.log(getTextExcept( document.querySelector(",container"). ";exclude-text" ));
 <div class="container"> <div class="exclude-text">Exclude me</div> <div class="another-class">Add this text</div> And this text here </div>

An alternative approach is to clone the entire structure, remove the elements you don't want the text of, and then use .textContent on the result.另一种方法是克隆整个结构,删除不需要文本的元素,然后在结果上使用.textContent For a really large structure, that might be problematic in terms of memory (but it would have to be really large).对于一个非常大的结构,就 memory 而言这可能是有问题的(但它必须非常大)。

 function getTextExcept(element, exclude) { const clone = element.cloneNode(true); for (const child of clone.querySelectorAll(exclude)) { child.remove(); } return clone.textContent; } console.log(getTextExcept( document.querySelector(".container"), ".exclude-text" ));
 <div class="container"> <div class="exclude-text">Exclude me</div> <div class="another-class">Add this text</div> And this text here </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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