Home > database >  How to find a list item with an id in a list of items?
How to find a list item with an id in a list of items?

Time:11-22

I have a list of keywords that I want to filter based on <li id="newKeyword">:

<ul id="keywordList">
  <li></li>
  <li id="newKeyword"></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

When I click a button, the function showNewKeywords() triggers:

function showNewKeywords() {
  // Declare variables
  var ul, li;

  ul = document.getElementById("keywordList");
  li = ul.getElementsByTagName('li');


  // Loop through all list items, and hide those who don't have the li ID
  for (i = 0; i < li.length; i  ) {

    // Find id of each li within the list
    
  }
}

I have difficulties looping through the list of li tags to find the ones with the id. I tried the getElementById method, but that goes through the entire file (I think).

Any tips on how to filter through a list of li based on the li id?

Thanks so much!

Edit: fixed typos.

CodePudding user response:

When you loop you need to get li element, I assigned to a variable, and get its id put it inside txtValue and test for that if is not equal (!=) then remove it with affect it a style of display:none:

function showNewKeywords() {
  // Declare variables
  var ul, li;

  ul = document.getElementById("keywordList");
  li = ul.getElementsByTagName('li');


  // Loop through all list items, and hide those who don't have the li ID
  for (i = 0; i < li.length; i  ) {
    //vvvv
    a = li[i];
    // My main problem here
    //a = "find id of each li within the list";
    txtValue = a.id;

    // This is a secondary problem but I'll figure it out
    if (txtValue!='newKeyword') {
      a.style.display = "none";
    }
  }
}
<ul id="keywordList">
  <li></li>
  <li id="newKeyword"></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
<button onclick="showNewKeywords()">show New Keywords</button>

PS: choose better naming of variables: instead of a name it with currentLI which has more sense, and also for txtValue replace it with idOfCurrLI.

  • Related