I'm trying to assign a specific CSS class to specific rows of my <h:dataTable>. Is there some way to access and cutomize the resulting table rows?
- 1,082,665
 - 372
 - 3,610
 - 3,555
 
- 7,871
 - 9
 - 36
 - 46
 
2 Answers
Bind the rowClasses attribute to a bean property which returns the desired string of CSS classes.
<h:dataTable value="#{bean.list}" rowClasses="#{bean.rowClasses}">
with e.g.
public String getRowClasses() {
    StringBuilder rowClasses = new StringBuilder();
    for (Item item : list) {
        if (rowClasses.length() > 0) rowClasses.append(",");
        rowClasses.append(item.getRowClass());
    }
    return rowClasses.toString();
}
Update to clarify, this way you have full programmatic control over the rowClasses string. Note that the above is just a kickoff example, it doesn't necessarily need to be obtained by Item#getRowClass() or so. You can even do it in a simple for loop with a counter.
E.g.
public String getRowClasses() {
    StringBuilder rowClasses = new StringBuilder();
    for (int i = 0; i < list.size(); i++) {
        if (rowClasses.length() > 0) rowClasses.append(",");
        rowClasses.append(selected.contains(i) ? "selected" : "none");
    }
    return rowClasses.toString();
}
where selected is a List<Integer>. If it contains 1, 2 and 5, then the returned string will look like as follows for a list of 10 items:
none,selected,selected,none,none,selected,none,none,none,none
- 1,082,665
 - 372
 - 3,610
 - 3,555
 
- 
                    Thank you BalusC, but I meant assign a specific class to a single specific row: e.g. assign CSS class "redRow" to 3rd row. rowClasses let me specify a repeating schema for all rows. – Pier Luigi Dec 10 '10 at 12:38
 - 
                    1Just let the 3rd item return `redRow` on `getRowClass()`. Or use a counter and append `redRow` on 3rd item. Do you understand the point of the given answer anyway? – BalusC Dec 10 '10 at 12:51
 
I like @BalusC suggestion. If you want a second alternative, you can do this easily with javascript/JQuery.
With JQuery you can do it like this
(Note, this is just an example. I haven't tested it, and there is probably a better way of doing it)
$(document).ready(function(){
  var counter = 0;
  $('#myTable').each(function() {
      counter = counter + 1;
      if(counter==3) {
        $(this).addClass('redRow');
        return;
      }
    
  });
}
- 19,370
 - 6
 - 64
 - 102
 
- 23,901
 - 30
 - 103
 - 143