[英]Extract and combine all text child nodes
Suppose I have a node list created by appending text child nodes dynamically as following:假设我有一个通过动态附加文本子节点创建的节点列表,如下所示:
const container = document.getElementById('container') for (var i = 0;i < 5;i++) { let containerChild = document.createTextNode('a') container.appendChild(containerChild) }
<div id="container"></div>
Assuming that only text nodes are appended, what is the fastest / most clean way to extract the full text?假设只附加了文本节点,那么提取全文的最快/最干净的方法是什么? In the case above, I am looking to get the string
aaaaa
.在上面的例子中,我希望得到字符串
aaaaa
。 Of course I can loop through the parent node container
to extract each child and then combine them.当然,我可以循环遍历父节点
container
来提取每个子节点,然后将它们组合起来。 Just wondering if there is a better way.只是想知道是否有更好的方法。 Thanks.
谢谢。
The .textContent
of the parent will combine them automatically:父级的
.textContent
会自动组合它们:
const container = document.getElementById('container') for (var i = 0;i < 5;i++) { let containerChild = document.createTextNode('a') container.appendChild(containerChild) } const text = container.textContent; console.log(text, text.length);
<div id="container"></div>
( .innerHTML
works too) (
.innerHTML
也可以)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.