tags:

views:

106

answers:

2

I am trying to explore any possible coding option that I can use to simplify my code or have a better flexibility on writing the code. If I have this element nest..

<table>
   <tr><td></td><td></td></tr>
   <tr><td></td><td></td></tr>
   <tr><td></td><td></td></tr>
   <tr><td></td><td></td></tr>
</table>

if I want to write text on first columns, I can do

$("table tr").each(function({
  // how to write text here on all first column using $(this)?
  // other ways to write on first column?
});

// other ways to write all first column not using ".each"

+4  A: 

You can use the first selector:

$('table tr td:first').each(function(){
    $(this).text('1st column');
});

Or without using each:

$('table tr td:first').text('1st column');


I hope I got your comment right. If you do not want to use first for some reason, you could check whether prev() is empty inside your call to each().

if ($(this).prev().length == 0){
    // $(this) references the first column
}
middus
I know it sound inefficient, but is there a way to write it using the ".each" and $(this)? I am trying to see the capabilities of jquery.
kratz
Instead of do stuff, I'd suggest .each( function() { ... } ), unless of course, you've got a *doStuff* plugin.
tvanfosson
+1  A: 
$("table tr").each(function({
    $(this).find('td:first').text('Some text');
});
meanstreakuk
Not as good as adding the td:first to the original selector, but meets the OP's stated goal of using $(this) inside each. I had this (except I used html()) written when I saw your answer pop up.
tvanfosson