0

In the statement

var length = $(this).parent().parent().parent().children('tr').length;

where $(this).parent().parent().parent() part gives us a <tbody> element, which happens to have more than one tr children.

1. So which tr among those children of tbody returned by $(this).parent().parent().parent() is this particular tr whose length is going to be returned by the .length property?

............................................

From the documentation of the length property,

Description: The number of elements in the jQuery object.

I understand it as: The 'jQuery object' here is a tr element which is a child of the tbody returned by $(this).parent().parent().parent(), and 'the number of elements' in this jQuery object is the number of tds in this tr. So the .length property here will return the number of tds in the tr under consideration, right?

2. But in the example given here (I am copying the code below for reference), the statement

var n = $( "div" ).length;

assigns n the number of divs in the body. But shouldn't it rather contain the number of elements in the/direct children of a div?

1. And again, which div's length will be returned if different divs have different lengths?

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>length demo</title>
  <style>
  body {
    cursor: pointer;
  }
  div {
    width: 50px;
    height: 30px;
    margin: 5px;
    float: left;
    background: green;
  }
  span {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
  <span></span>
  <div></div>
<script>
$( document.body )
  .click(function() {
    $( document.body ).append( $( "<div>" ) );
    var n = $( "div" ).length;
    $( "span" ).text( "There are " + n + " divs." +
      "Click to add more.");
  })
  // Trigger the click to start
  .trigger( "click" );
</script>

</body>
</html>
Solace
  • 8,612
  • 22
  • 95
  • 183
  • 1
    `length` *does not* find *content length*, it finds *size(number) of objects*. You are complicating it. The `length` property returns the **size** of list of matching elements in the preceding object. That is it! To calculate length/size of children of `div`, `$('div').children().length()` needs to be used. – Shaunak D Apr 28 '15 at 09:59
  • @ShaunakD " returns the size of list of matching elements in the preceding object" - thank you for this, I think I understand it now. – Solace Apr 28 '15 at 10:08

1 Answers1

2

Considering jQuery objects length does not mean content length inside a particular object.

length returns the size/number of matching elements.

$(this).parent().parent().parent().children('tr')  .  length
|_______________________________________________|     |____|
                         |preceding object               |Size of the preceding list

So, if <tbody> has 4 <tr>s - length will return 4.

Shaunak D
  • 20,588
  • 10
  • 46
  • 79