views:

28

answers:

1

I've got a fiddle going here to show what I'm trying to do.

I have a table that is generated dynamically, so the columns could appear in whatever order the user chooses. So, I'm trying to get the index of two specific headers so that I can add a CSS class to those two columns for use later.

+2  A: 

You should use .filter() here instead (and whenever you need to restrict the element set), since your .each() return is getting thrown away, like this:

//Loop thru the headers and get the Supp elem
var suppCol = $("#my_table th").filter(function() {
    return $(this).html() == "Supp";
});
//Loop thru the headers and get the Report elem
var reportCol = $("#my_table th").filter(function() {
    return $(this).html() == "Report";
});

You can test the updated/working fiddle here. The alternative using .each() would look like tis:

var suppCol, reportCol;
$("#my_table th").each(function() {
    var $this = $(this), html = $this.html();
    if(html == "Supp") suppCol = $this;
    if(html == "Report") reportCol= $this;
});

You can test that version here.

Nick Craver
Let me make sure I'm getting this right: the `.each(function() {return})` was basically returning the result to nothing since it was iterating and not actually able to assign my value to anything, right?
kchau
@kchau - Not sure I'm following 100%, but it was returning *every* `<th>`, basically what you had was the same as `var suppCol = $("#my_table th");`, since `.each()` just *returns* the set that it's run on...it's for running someone on every element, but not changing the set, what's exactly what `.filter()` is for :)
Nick Craver
@Nick, I see what I did wrong now. Thanks for the quick response!
kchau
@kchau - welcome! :)
Nick Craver
@Nick, PS - your second example for `.each()` alternative is still using `.filter()`. :-P
kchau
@kchau - woops updated, it still works just more expensive and an inappropriate usage :)
Nick Craver