开发者

jquery .children() returning wrong size

I just found the children size not consistent.

Below attach full code with alert, for easy reference.

Is the way I get the data wrong?

<body>
<table width="100" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td height="30" valign="top"><strong>Header Title</strong></td>
      </tr>

      <tr>
          <td height="32" valign="top">Date : <strong>01/01/2010 </strong> <br><div><b></b&g开发者_StackOverflowt;</div><span></span></td>
      </tr>
</table>
</body>

$("td").each(function() {
    alert($(this).children().size());   
});

//first td showing 1 direct children- <strong>
//second td showing 4 direct children- <strong> <br> <div> <span>

-----

$("tr").each(function() {
    alert($(this).children().size());   
});

//first tr showing 1 direct children - <td>
//second tr showing 1 direct children - <td>

-----

$("table").each(function() {
    alert($(this).children().size());   
});

// ERROR
// this table showing 1 direct children only.... something WRONG.
// I thought there are 2 <tr> inside this table?


The reason is that you don't have a <tbody> within your table. The browser adds this automatically for you, and hence it becomes the only child of <table>.

You may be interested in running this piece of code:

alert($('table').children()[0].tagName);


You're asking the size of the td's children, and in your structure, your td only has one child: the strong tag.

In your second, you are asking the children of your trs. Each of your tr tags only have 1 td, thus it is showing 1 only.

Try this:

alert($("tbody").children().length)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜