Reputation: 1815
Having a table like:
<table id="table_1">
<tr><td>1</td><td>foo</td></tr>
<tr><td>2</td><td>foo</td></tr>
<tr><td>3</td><td>foo</td></tr>
<tr><td>4</td><td>foo</td></tr>
</table>
I want to get the first td of each table row. Then i want to iterate through the findings and compare the text value contained in the td with a value i have.
So far, i can get the first td of each tr by using the following :
var test = $("#table_1").find('td:first-child');
Then i get the number of tds : console.log(test.length);
but when i try to get the text of a td i get an error : console.log(test[1].text());
Error:
Uncaught TypeError: test[1].text is not a function
Obviously i do something wrong. Is my way of thinking wrong? How can i fix it?
Upvotes: 0
Views: 1097
Reputation: 3646
console.log(test[1].text());
test -> is an array of htmlDomElement
when you say test[1] ->
it gives you a htmlElement not a jQuery object of that element, so you can not use .text()
which is jQuery function.
Wrap it with $(test[1]).text()
to make it jQuery object to use text()
function on it.
Upvotes: 0
Reputation: 82241
test
is jquery object of all first child elements. You should be using .eq(0)
or .first()
to target first element in the collection:
console.log(test.eq(0).text());
or
console.log(test.first().text());
Update: To get all the texts of first-child td elements in array
var allfirsttdtext = test.map(function(){
return $(this).text();
}).get();
Upvotes: 2
Reputation: 32354
Try this:
var v = 'compare';
$('#table_1 td').each(function () {
if ($(this).text() == v)
console.log($(this).text()+' is equal with the variable '+v);
})
Upvotes: 0
Reputation: 11137
You have to surround by jQuery as the resulted array is a Dom Elements:
for(i = 0; i < test.length; i++){
console.log($(test[i]).text())
}
Upvotes: 0
Reputation: 9637
use textContent in JavaScript bcoz u are converting jquery object into javascript object
console.log(test.eq(0).text());
or
console.log(test[0].textContent);
Upvotes: 0
Reputation: 133403
test[1]
will return underlying DOM element and .text()
is a jQuery function thus you are getting the error.
I think, You need to use .eq()
Reduce the set of matched elements to the one at the specified index.
Code
test.eq(0).text()
Note: that the supplied index is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree.
OR, Use textContent
test[1].textContent
Upvotes: 0