Reputation: 180
If my table looks like this in html
<table>
<tr>
<td>foo
<td>bar
<td>alpha
<td>beta
<td>seta
</tr>
<tr>
<td>foo1
<td>bar2
<td>alpha3
<td>beta3
<td>seta3
</tr>
</table>
And i was just going through jQuery for formatting the table.
//this one perfectly works
//this turns even columns into red!!
$("td").filter(':odd').addClass('colorRedClass');
But I want to use a function like this for the same! Is it possible?
//i returned the value ':odd' from the function!!
//this turns every column into red!!
//this is not working as expected!!
$("td").filter(function(){
return ':odd';
}).addClass('colorRedClass');
And colorRedClass is in CSS that has attribute color:red;
So, my question is, why can't the second one work? Why can't second one just change even columns into red? I am from c,c++, java background and as per my understanding, the return should work if I did the same way in those languages.
What am I missing?
Upvotes: 0
Views: 38
Reputation: 5685
The function you pass to filter is supposed to have the type:
Type: Function( Integer index, Element element ) => Boolean
So it expects you to return true if the element is to be included in the filtered set rather than use a selector.
You could use the index parameter to decide whether the element is odd:
$("td").filter(function(index){
var isOdd = index % 2 === 1;
return isOdd;
}).addClass('colorRedClass');
Upvotes: 3