Home > other >  filter HTML list with JS
filter HTML list with JS

Time:05-01

I am not very familiar with HTML and JavaScript, so my learning is based on reverse engineering code.

The code I'm using filters a table based on a keyword modified I can also add this code to a button and filter on a keyword I've added a very primitive toggle which works (well toggles anyways). However, I can't get the table to change all the styles back to style="Display = ""; at least I can't make them reappear?

var myTog = 0;

function myFunction() {
  var ul, li, a, i, txtValue;

  if (myTog == 0) {
    myTog = 1;

    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");

    for (i = 0; i < li.length; i  ) {
      a = li[i].getElementsByTagName("a")[0];
      txtValue = a.textContent || a.innerText;
      if (txtValue.indexOf("Cindy") > -1) {
        li[i].style.display = "";
      } else {
        li[i].style.display = "none";
      }
    }

  } else {
    alert("test if toggel works");

    // ================
    // Trouble Section:
    // ================

    for (i = 0; i < li.length; i  ) {
      li[i].style.display = "";
    }

    // ===============

    myTog = 0;
  }

}
<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>

  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>

  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>
<button type="button" onclick="myFunction()">Click Me!</button>

CodePudding user response:

if you are trying to display the li, then you can use something along the lines of:

li[i].style.display = "block";

CodePudding user response:

You must define your li = ul.getElementsByTagName("li"); outside of if clause

var myTog = 0;

function myFunction() {
  var ul, li, a, i, txtValue;
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName("li");

  if (myTog == 0) {
    myTog = 1;
    for (i = 0; i < li.length; i  ) {
      a = li[i].getElementsByTagName("a")[0];
      txtValue = a.textContent || a.innerText;
      if (txtValue.indexOf("Cindy") > -1) {
        li[i].style.display = "";
      } else {
        li[i].style.display = "none";
      }
    }
  } else {
    for (i = 0; i < li.length; i  ) {
      li[i].style.display = "";
    }
    myTog = 0;
  }
}
<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>

  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>

  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>
<button type="button" onclick="myFunction()">Click Me!</button>

  • Related