JavaScript 操作 HTML 文档与 CSS 样式全解析
1. Node 遍历 API 与文本内容获取
在处理 HTML 文档时,有时需要获取元素内的所有文本内容。以下是一个用于返回元素或文档内所有文本的函数示例:
// Return the plain-text content of element e, recursing into child elements.
// This method works like the textContent property
function textContent(e) {
let s = ""; // Accumulate the text here
for(let child = e.firstChild; child !== null; child = child.nextSibling) {
let type = child.nodeType;
if (type === 3) { // If it is a Text node
s += child.nodeValue; // add the text content to our string.
} else if (type === 1) { // And if it is an Element node
s += textContent(child); // then recurse.
}
超级会员免费看
订阅专栏 解锁全文
1615

被折叠的 条评论
为什么被折叠?



