如何一次性从指定CSS选择器提取所有<strong>标签的文本值至列表
一次性提取所有
<strong>标签文本到列表的方法 嘿,这事儿其实挺容易搞定的!你已经用document.querySelectorAll("p > strong")拿到了目标元素的NodeList,接下来只需要把这个类数组对象转换成真正的数组,再批量提取文本就行啦。给你分享几种实用的方法:
方法1:用Array.from()转换并映射
这是最直观的方式,Array.from()可以直接把NodeList转换成数组,接着用map()遍历每个元素提取文本:
const strongTexts = Array.from(document.querySelectorAll("p > strong")).map(el => el.innerText);
方法2:用扩展运算符(...)简化代码
扩展运算符能快速把NodeList展开成数组元素,写法更简洁:
const strongTexts = [...document.querySelectorAll("p > strong")].map(el => el.innerText);
兼容旧环境的方案(比如IE)
如果你的代码需要兼容不支持ES6语法的旧浏览器,可以用Array.prototype.slice.call()来转换:
const strongElements = document.querySelectorAll("p > strong"); const strongTexts = Array.prototype.slice.call(strongElements).map(el => el.innerText);
额外优化:过滤空文本
如果有些<strong>标签里可能只有空格或者空内容,你可以再加一步过滤,只保留有效文本:
const strongTexts = [...document.querySelectorAll("p > strong")] .map(el => el.innerText.trim()) // 先去除首尾空格 .filter(text => text); // 过滤掉空字符串
这样处理完,strongTexts就是一个包含所有目标文本的数组啦,直接用就行~
内容的提问来源于stack exchange,提问作者B4b4j1
相关产品推荐
相关产品推荐

