Question:
Something got confused. Why is that? how to fix?
var longtext = document.querySelector('.excerpt>p:nth-child(2)');// <p>long long text</p>
var cuttext = longtext.slice(0, 40); // Uncaught TypeError: longtext.slice is not a function
if (cuttext.length < longtext) {
cuttext += "...";
}
Answer:
The used document.querySelector
method only returns one element, not an array.
Therefore, a further attempt to take the first forty elements (?) From one looks strange.
To get a collection of elements, you need to use the document.querySelector All
method.
Which returns a collection of suitable elements, however, the returned collection does not have a slice
method, and in order to use it, you either need to borrow it from the array, or convert the resulting collection directly to an array, for example using Array.from
var longtext = Array.from(document.querySelectorAll('.excerpt>p:nth-child(2)'));
var cuttext = longtext.slice(0,40); //Uncaught TypeError: longtext.slice is not a function
if (cuttext.length < longtext.length) {
cuttext+="...";
}
However, judging by the names of the variables, it can be assumed that work is expected with text , not html elements. In this case, to get the text of the selected element, you had to use the textContent
method, or if you need to get the text including html tags, innerHTML
var longtext = document.querySelector('.excerpt>p:nth-child(2)').textContent;//long long text
var cuttext = longtext.slice(0,40); //Uncaught TypeError: longtext.slice is not a function
if (cuttext.length < longtext.length) {
cuttext+="...";
}