Reputation: 151
I'm making a plug-in where I can shorten the title of each entry in a forum index if it is too long. However, that is much harder than I expected.
Everything goes fine except when I get to the part where you actually have to print the items onto the DOM.
I get this error:
Uncaught TypeError: undefined is not a function
Here is my code with a bunch of notes I left to show you how it works.
var minimize = function() {
$('.segment').each(function(){
var title_box = $(this).children('.title');
// Selects the container of the title.
var title = $(this).children('.title').text().trim();
// Takes the child title of the each .segment class and selects its innards.
console.log(title);
var res = title.split("");
// Splits the text into an array.
console.log(res);
var fragment = [];
// initializing the empty array
for (x = 0; x < 4; x++) {
fragment.push(res[x]);
console.log(fragment);
// Loops through to make sure it's not more than 5 characters long
};
var final = fragment.join("");
// Joins the broken up string together.
title_box.empty();
final.appendTo(title_box);
});
};
What do you think I did wrong? And if there's any other ways for me to make this code more efficient, then please don't hesitate to tell me.
Upvotes: 0
Views: 1009
Reputation: 45135
Right here you define fragment
as an array:
var fragment = [];
You then populate it and do this:
var final = fragment.join("");
Read the docs on array.join to understand what that function does. In short, it joins your array together into a string
So now when you do this:
final.appendTo(title_box);
You get your TypeError
because string doesn't have an appendTo
method
What you probably wanted was a jquery object to call appendTo
on.
Perhaps you meant:
title_box.text(final);
Upvotes: 2