You are nearly there.
Since there is no class named 0 exists, you can start the loop at i=1 and end when i<=val. I think you do not need the if condition here.
var val = 3;
for(var i=1; i<=val; i++){
$('.'+i).addClass("somecl");
}
.somecl{color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="a 1">11</td>
<td class="a 2">22</td>
<td class="a 3">33</td>
</tr>
<tr>
<td class="b 4">44</td>
<td class="b 5">55</td>
<td class="b 6">66</td>
</tr>
</table>
Few Alternative Solutions:
You can use .each() to iterate over all the td to check if the element has the class or not. If has then add the class.
Please Note: index start from 0, that means 0 for first, 1 for second element and so on.
var val = 3;
$('td').each(function(i){
var i = i+1;
if($(this).hasClass(i) && i <= val)
$(this).addClass("somecl");
});
.somecl{color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="a 1">11</td>
<td class="a 2">22</td>
<td class="a 3">33</td>
</tr>
<tr>
<td class="b 4">44</td>
<td class="b 5">55</td>
<td class="b 6">66</td>
</tr>
</table>
You can use .eq() to reduce the set of matched elements to the one at the specified index.
var val = 3;
for(var i=0; i<val; i++){
$('td').eq(i).addClass("somecl");
}
.somecl{color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="a 1">11</td>
<td class="a 2">22</td>
<td class="a 3">33</td>
</tr>
<tr>
<td class="b 4">44</td>
<td class="b 5">55</td>
<td class="b 6">66</td>
</tr>
</table>
You can also get all the elements in a variable, then use loop to set the class with the current i value as the index of the element in the variable.
var el = $('td');
var val = 3;
for(var i=0; i<val; i++){
$(el[i]).addClass("somecl");
}
.somecl{color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="a 1">11</td>
<td class="a 2">22</td>
<td class="a 3">33</td>
</tr>
<tr>
<td class="b 4">44</td>
<td class="b 5">55</td>
<td class="b 6">66</td>
</tr>
</table>