Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following HTML structure and I wanted to find out the length of immediate <td>s. here is the code that I am using:-

<table class="PrintTable">
    <tr>
      **<td>**
        <table>
            <thead>
                <tr><th>Type Of Transaction</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td>Name</td>
                </tr>
                <tr>
                    <td>Age</td>
                </tr>
            </tbody>
        </table>
      </td>
      **<td>**
        <table>
            <thead>
                <tr><th>2006</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td>Andi</td>
                </tr>
                <tr>
                    <td>25</td>
                </tr>
            </tbody>
        </table>
      </td>

    </tr>
</table>

The function that I am using to find out the length of td is

function getBody(element)
{
    var divider=2;
    var originalTable=element.clone();
    var tds = $(originalTable).children('tr').children('td').length;
    alert(tds);


}

The result I am seeing is 0. No clue at all. I am expecting 2. Any help will be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
552 views
Welcome To Ask or Share your Answers For Others

1 Answer

I removed the asterisks out of your HTML and made some assumptions about how you're invoking getBody, so if I did anything that wasn't right, let me know.

Code: http://jsfiddle.net/27ygP/

function getBody(element) {
    var divider = 2;
    var originalTable = element.clone();
    var tds = $(originalTable).children('tbody').children('tr').children('td').length;
    alert(tds);
}

getBody($('table.PrintTable'));

The big change was the add a .children('tbody'). The HTML interpreter wraps the trs in tbody. Traverse down into that, and you'll be fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...