AngularDoubts AngularDoubts - 6 months ago 12
HTML Question

Show all child <ui> and <li> within an <li> tag using jquery

I have a nested 'ul' 'li' tree. On an instance, I show only certain 'li' based on a particular name and others are hidden. SAy, I have a tree like this:


  • branch1


    • twig1


      • leaf1


    • twig2


  • Branch2


    • twig3




What I need is when I filter branch1 it should show twig1, twig2 and leaf1 as well(). Now it shows only parent branch1. How can I show child nodes too? I give the text to filter as input via a text box. Please help me... Thanks in advance.



$(document).ready(function() {
$('input[type="text"]').keyup(function() {

var filter = jQuery(this).val();
jQuery("ul li").each(function() {
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
jQuery(this).hide();
} else {
jQuery(this).show();
jQuery(this).children().show();
}
});
});

function func() {
alert("Onclick function...");
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" />

<ul id="mytree">
<li>
Branch1
<ul>
<li>twig1
<ul>
<li>leaf1</li>
</ul>
</li>
<li>
twig2
</li>
</ul>
</li>
<li>
Branch2
</li>
</ul>




Answer

Try like this

      $('input[type="text"]').keyup(function() {

        var filter = jQuery(this).val();
        jQuery("#mytree>li").each(function() {
          if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
              jQuery(this).hide();
          } else {
            jQuery(this).show();
            jQuery(this).find('li').show();
          }
        });
      });

      function func() {
        alert("Onclick function...");
      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" />

<ul id="mytree">

  <li>
    Branch1
    <ul>
      <li>twig1
        <ul>
          <li>leaf1</li>
        </ul>
      </li>
      <li>
        twig2
      </li>
    </ul>
  </li>
  <li>
    Branch2
  </li>
</ul>

.text() function returns text of element including subitems. So you don't need to cycle every li item. Only "root" items are enough.