Search code examples
javascriptsearchfilterforeachjquery-selectors

Foreach loops only through the last column of the table (ES6)


I was trying to build my first search function for a phonelist. Unfortunately it looks like, my filter function loops only trough the last column of the table. Did i miss something? Or do i have to use a different approach for this?

PS: Pardon for the possible duplicate. All examples that i've found has been for PHP.

Many thanks in advance!

const phonelist = document.querySelector('table');
const searchInput = document.querySelector('#search');
const searchResult = document.querySelector('#search-result');
const searchValue = document.querySelector('#search-value');

// EVENTS
function initEvents() {
  searchInput.addEventListener('keyup', filter);
}

function filter(e) {
  let text = e.target.value.toLowerCase();
  console.log(text);

  // SHOW SEARCH-RESULT DIV
  if (text != '') {
    searchValue.textContent = text;
    searchResult.classList.remove('hidden');
  } else {
    searchResult.classList.add('hidden');
  }

  document.querySelectorAll('td').forEach((row) => {
    let item = row.textContent.toLowerCase();

    if (item.indexOf(text) != -1) {
      row.parentElement.style.display = 'table-row';
      console.log(row.parentElement);
    } else {
      row.parentElement.style.display = 'none';
    }
  })
}

// ASSIGN EVENTS
initEvents();
<input id="search" />

<div class="phonelist">
  <div id="search-result" class="hidden">
    <p>Search results for <b id="search-value"></b>:</p>
  </div>
  <table class="striped">
    <thead>
      <tr>
        <th>Phone</th>
        <th>Fax</th>
        <th>Room</th>
        <th>Name</th>
        <th>Title</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>165</td>
        <td>516</td>
        <td>1.47</td>
        <td>Johnathan Doe</td>
        <td>Sales</td>
      </tr>
      <tr>
        <td>443</td>
        <td>516</td>
        <td>1.47</td>
        <td>Jane Dow</td>
        <td>Development</td>
      </tr>
    </tbody>
  </table>
</div>


Solution

  • it looks like you are querying the wrong element

      document.querySelectorAll('td').forEach((row) => {
    

    I think you want to be querying the row

      document.querySelectorAll('tr').forEach((row) => {
    

    otherwise you are of overriding your class changes with whatever is the result of the last column

    (and obviously apply the class on the tr and not the parent of the tr)