-3

I am trying to truncate the text content of every element (text from a paragraph) in an array, so that I have just the first five characters of the text contained by the element.

Here is the code I already have:

// 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));

If I do this:

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

It gives me this error:

Uncaught TypeError: paragraphs[0].substring is not a function

CodePen : https://codepen.io/balincagabrielalin/pen/abNMVxv

Zeth
  • 41
  • 8

2 Answers2

3

You probably want to take a substring of the element's textContent.

console.log(paragraphs[0].textContent.substring(0, 5));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
2

Just socket the textContent function

var text = document.getElementsByClassName("truncate");
var paragraphs = new Array();
for (var i = 0; i < text.length; i++) {
  paragraphs.push(text[i].querySelector("p"));
  console.log(paragraphs[i].textContent.substring(0, 5));
}
<div class="truncate">
  <p>Hello world</p>
</div>
<div class="truncate">
  <p>Hell world</p>
</div>
Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39