1

There is the following code with jQuery:

var ths = $(".timetable__table th");
var th;

    for (var i = 0; i < ths.size(); i++) {
      th  = ths.get(i).text();
      console.log(th);
    }  

When I try to execute this code I get the following exception: TypeError: ths.get(...).text is not a function. I don't understand why it occurs, I just need to get the text value of a tag. How can I fix it?

4 Answers 4

2

Do like this, Use .each() function at this context to traverse over a collection of jquery object.

$(".timetable__table th").each(function(){
 console.log($(this).text());
});

.get(index) would return a javascript object and that does not contains a function called .text()

Note: Keep in mind that .size() has been deprecated from the version 1.8 use .length instead

Sign up to request clarification or add additional context in comments.

Comments

1

because .get() returns the dom element not a jQuery object(the .text() is a method of jQuery wrapper object) use .eq() which will return a jQuery object

var ths = $(".timetable__table th");
var th;

for (var i = 0; i < ths.size(); i++) {
    th = ths.eq(i).text();
    console.log(th);
}

Comments

0

You need to iterate array like th[i] :

var ths = $(".timetable__table th");
var th;

    for (var i = 0; i < ths.size(); i++) {
      th  = ths[i].text();
      console.log(th);
    }  

But easiest way is below where you can skip for loop and simply use .each :

$(".timetable__table th").each(function(){
   console.log($(this).text());
});

Comments

0

.get() returns the underlying DOM element(s), which don't have a text() method. Use .eq() instead.

Looks like you didn't decide if you want to use the DOM or jQuery. Your code can be simplified to something like:

$(".timetable__table th").each(function(index, el) {
    console.log($(el).text());
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.