How to populate a list based on a table and its rows in Dart?

I want to populate a list of objects based on an HTML table. Let's say I have the following class:

class Employee { String name; String department; num salary; ...methods } 

And in my HTML, I have the following table:

 <table class="table" id="employeeTable"> <thead> <tr> <th>Name <th>Departament <th>Salary <tbody id="employeeTableBody"> <tr> <td> John <td> 1 <td> 1500 <tr> <td> Mary <td> 2 <td> 2500 ...etc </table> 

So, how can I query a table, get its rows, and then get its cells to populate my list of employees (in this case)?

I tried using something like:

  TableElement table = query("#employeesTable"); Element tableBody = query("#employeesTableBody"); 

But I could not find the correct method in the TableElement or Element to return a TableRowElement or, possibly, its cells. I also tried to get child nodes, but without success.

The pseudo-algorithm for performing this task will be something like this:

 1. Get the table 2. For each row of the table 2.a Create a new Employee object based on the value of each cell of the row. 2.b Append this object to the Employee List. 3. End 
+3
source share
1 answer

Here's the HTML:

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Scratchweb</title> <link rel="stylesheet" href="scratchweb.css"> </head> <body> <table id="employeeTable"> <tr> <th>Name</th> <th>Departament</th> <th>Salary</th> </tr> <tr> <td>John</td> <td>1</td> <td>1500</td> </tr> <tr> <td>Mary</td> <td>2</td> <td>2500</td> </tr> </table> <script type="application/dart" src="web/scratchweb.dart"></script> <script src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script> </body> </html> 

Here's the Dart:

 import 'dart:html'; import 'dart:math'; class Employee { String name; String department; num salary; Employee({this.name, this.department, this.salary}); String toString() => '<employee name="$name" department="$department" salary="$salary">'; } void main() { var employees = new List<Employee>(); var table = query("table#employeeTable"); for (TableRowElement row in table.rows) { if (row.cells.length != 3) { print("Malformed row: $row"); continue; } if ((row.cells[0] as TableCellElement).tagName == "TH") { print("Skipping header"); continue; } var cells = row.cells; var employee = new Employee( name: cells[0].text, department: cells[1].text, salary: parseDouble(cells[2].text)); employees.add(employee); } print(employees); } 

If you approve of this answer, be sure to accept it. My boss feeds me a piece of bacon every time I successfully answer a question;)

+6
source

All Articles