首页 > 解决方案 > 如何仅获取元素文本的前 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

标签: javascript

解决方案


您可能想要获取元素的textContent.

console.log(paragraphs[0].textContent.substring(0, 5));

推荐阅读