children().length is returning an unexpected value

Everything can be found here: http://jsfiddle.net/dweiliu/NBFMq/3/

This is the relevant code in question:

$('article.weeklyStandings').each(function(){
   var numPlayers = $(this).children('table tr').length;
   $(this).children('h2').append(" - " + numPlayers + " Players");
});

I have potentially multiple tables of data with results as displayed in the jsfiddle. I want to point out the number of players who played on any given week by looking up the number of rows in the table.

Why is $(this).children('table tr').length; returning 0 on jsfiddle? Note that on my local machine, this same code is returning 3.

Answers


The problem you are having is:

  1. children() will only look at direct children. You'll want to use find() which will find all the table tr within each article.
  2. If you count all of the tr's you will have end up with an extra because your heading will also be counted as a player. For this reason you can subtract 1 from the length of tr's.

Solution

Here is an example implementing the above solutions: Demo

var numPlayers = $(this).find('table tr').length -1;

Alternative (the one I would use)

As you have a record class on your player tr's, you could use .record in your selector instead, this will provide better readability and flexibility if you wish to add other rows in the future that should not be counted as a player: Demo

var numPlayers = $(this).find('.record').length;

Another Alternative

You could also use context selectors like $('.record', this) instead of $(this).find('.record'), but in my opinion it's easier to read find() chaining. Also, as context selectors internally have to use find() anyway, using find() directly will perform slightly better: Performance test


Need Your Help

Crontab Creating Files with Dynamic File Names

file cron crontab

How can I set the crontab to create, say for example, text files with dynamic file names? What I mean is, for instance, I will set the crontab that a text file will be created every minute in a

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.