1

I'm creating a simple tree structure which holds input field as child. Each child consist of one input field and two buttons. One button is for adding child for the input and another for removing the node. My code is shown in below snippet and it's not working as expected. The problem is that : I can't add more than one child only one child is getting added.

$("#main").on('click', '.add', function() {
  var $td = $(this).parent();
  var $td1 = $('<td>', {
    html: '<input  />      <button class="add">        Add      </button>      <button class="remove">        Remove      </button>'
  });
  console.log($td.children('table').length);
  if ($td.children('table').length)
    $td.children('table').children('tr').append($td1);
  else
    $td.append($('<table>', {
      html: $('<tr>', {
        html: $td1
      })
    }))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="main" style="width:100%;text-align:center">
  <tr>
    <td>
      <input type="text" />
      <button class="add">
        Add
      </button>
      <button class="remove">
        Remove
      </button>
    </td>
  </tr>
</table>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    The browser parser add a `tbody` so this returns empty matched set: `$td.children('table').children('tr')`. Use `find()` instead `$td.children('table').find('tr')` – A. Wolff Apr 18 '16 at 11:13
  • 1
    @A.Wolff : yup you are correct , it's working after adding `children('tbody')` – Pranav C Balan Apr 18 '16 at 11:18
  • @A.Wolff : `$td.children('table').find('tr')` this will be much better and while appending I can use `eq(0)` to avoid nested `tr`. please add it as answer..... – Pranav C Balan Apr 18 '16 at 11:21

1 Answers1

3

Browser parser on all modern browsers (AFAIK?!) add TBODY element. For more details, see this answer.

In your case, this would make $td.children('table').children('tr') returning empty matched set, because children() is only targeting direct descendant (one level).

You could use instead find() method, matching any descendant:

$td.children('table').find('tr').append($td1);
Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155