javascript - 如何仅获取元素文本的前 5 个字符?
问题描述
我试图截断数组中每个元素(段落中的文本)的文本内容,以便我只有元素包含的文本的前五个字符。
这是我已经拥有的代码:
// Getting the div elements (this return an HTMLCollection )
var text = document.getElementsByClassName("truncate");
// Simple Array
var paragraphs = new Array();
// Going throught the HTMLCollection
for(var i = 0; i < text.length; i++){
// Selecting first paragraph from each div and pushing it into
// paragraphs array
paragraphs.push(text[i].querySelector("p"));
}
// For testing purposes I want to display in console first 5 letters from
// paragraph .substring(start, end) method extract characters from a
// string so this line should display first 5 characters from first element
// of the array
console.log(paragraphs[0].substring(0, 5));
如果我这样做:
console.log(paragraphs[0].substring(0, 5));
它给了我这个错误:
Uncaught TypeError: paragraphs[0].substring is not a function
代码笔: https ://codepen.io/balincagabrielalin/pen/abNMVxv
解决方案
您可能想要获取元素的textContent
.
console.log(paragraphs[0].textContent.substring(0, 5));
推荐阅读
- sql - 如何在 Redshift 中使用 UNLOAD 为文件名添加日期
- terraform - 通过 Terraform 在映射中通过命令行传递 vars
- javascript - 按多个键和值搜索,Javascript
- excel - Excel - 如何根据更改更新表格图片
- java - 使用spring生成sp元数据文件期间的用户定义值
- servicestack - 即使 UseDistinctRoleTables 为 false,也会创建 UserAuthRole
- python - 我们如何重新排序链表——反转后半部分并将每个相邻元素一个接一个地连接到前半部分?
- python - Azure Cosmos Python “系统中不存在具有指定 ID 的实体
- amazon-web-services - 标识符为 drawtest22 的 AWS::SageMaker::FeatureGroup 类型的资源不稳定
- python - Python 上的连接检查器脚本