I am building comment system with one level deep nested reply. My comment system is base on <ul> and <li> markups. Below is the tree example:

<ul class="comments">
  <li>comment text 1</li>
  <li>
    comment text 2
    <ul class="nested">
      <li>Reply 1 of comment text 2</li>
      <li>Reply 2 of comment text 2</li>
    </ul>
  </li>
</ul>

Comment is Ajax base (jQuery). My question is how to check if nested reply exists for a parent level comment? If it exist then I should be able to just append the new comment, if not then I should be able to create the child <ul class="nested"> node and then insert the returned html.

So taking the above example, If someone is replying to comment text 1, I should be able to create <ul> node first and then insert the returned <li> element. But if someone is replying to comment text 2. I should be able to append the returned <li> elements into the existing <ul> child node.

`

1 Answers

0
Alekhya On

We can check the existence of a child ".nested" by getting its length . If $(this) is your list Item li tag(comment text 1)...

<script>

    var comment = 'Reply 1 of comment text 1';
    if($(this).find('.nested').length > 0) {
        $(this).find('.nested').append('<li>'+comment+'</li>');
    } else {
        $(this).append('<ul class="nested"><li>'+comment+'</li></ul>');
    }

</script>