views:

48

answers:

2

I'm having trouble grabbing the TR count in JQuery of a table that inside a DIV set to be hidden.

Here is an example:

<div id="questions" style="display: none;">
<table id="tbl_questions">
<thead>
 <tr>
  <th>Question</th>
  <th>Weight</th>
 </tr>
</thead>
<tbody>
 <tr id="q0">
  <td id="td_question0">Some Question 0</td>
  <td id="td_wieght0">Some Weight 0</td>
 </tr>
 <tr id="q1">
  <td id="td_question1">Some Question 1</td>
  <td id="td_wieght1">Some Weight 1</td>
 </tr>
</tbody>
</table>
</div>

Note the table is within the containing div. It's set to display: none. When I try to run this JQuery code it returns 0.

var question_count = $("#tbl_questions> tr").size();
alert(question_count);

Any ideas?

I'm try to locate the count so I can then build an array of each question and weight in the table. Since the ID's provide me with an index this should be simple, but is the fact that it is contained in a hidden DIV going to be a problem just as the above question?

Thanks, Tegan Snyder

+2  A: 

Your selector says, "all tr elements that are direct children of the element whose 'id' value is 'tbl_questions'". There are no such "tr" elements.

Get rid of the ">" in the selector and see if that helps. When you're just looking for elements somewhere "down below" a particular container, you don't need (or want) the ">", which means to look only one level down (i.e., at direct children).

Pointy
+2  A: 

Try:

var question_count = $("#tbl_questions tbody tr").size();

That will pick up rows which are descendants of the tbody which descends from #tbl_questions, irrespective of the nesting depth. See http://api.jquery.com/descendant-selector/.

The following should also work, as the tbody is a direct child of #tbl_questions, and the tr's containing your questions are direct children of the tbody element:

var question_count = $("#tbl_questions > tbody > tr").size();

Also see http://api.jquery.com/child-selector/

karim79