Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

Hide rows in a column with vanilla JavaScript according to text content

I have a table like this:

<table id="mytable" class="table">
    <tr>
        <th>Author</th>
        <th>Title</th>
        <th>Year</th>
        <th>Digitised</th>
    </tr>
</table

I'd like to have a button which, when clicked, hides or shows the rows which contain a 'Yes' (or a check, or a specific element) in the 'Digitised' column.

This is the JavaScript I've come up so far

      let table, tr, td, i, t;
      table = document.getElementById("myTable");
      tr = table.getElementsByTagName("tr");
      for(t=0; t<tds.length; t1++) {
                let td = tds[t][3];
                if (td) {
                  if (td.innerHTML.indexOf('Yes') > -1) {
                    tr[i].style.display = 'none';
                  }
                }
            }
        }

This doesn't work. How can I achieve what I want?

question from:https://stackoverflow.com/questions/65598625/hide-rows-in-a-column-with-vanilla-javascript-according-to-text-content

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have the wrong id in your Javascript, the table id is "mytable" (in lower case) but your js code is trying to find "myTable" which is camel case,

Anyways here is a sample of code that do what you need:

var areRowsDisplayed = true

function toggleRows() {
    const rows = document.querySelectorAll('#mytable > tbody > tr')
  Array.prototype.slice.call(rows).forEach(row => {
    let dataField = row.querySelectorAll('td')[3]
    if(dataField.innerText.toLowerCase() == 'yes') {
      row.style.display = !areRowsDisplayed ? '': 'none'
    }
  })
  areRowsDisplayed = !areRowsDisplayed
}

document.querySelector('#toggleRows').addEventListener('click',e => toggleRows())
<button id='toggleRows'>Hide/Show</button>
<table id="mytable" class="table">
  <thead>
    <tr>
        <th>Author</th>
        <th>Title</th>
        <th>Year</th>
        <th>Digitised</th>
    </tr>
    </thead>
    <tbody>
      <tr>
        <td>Pin Pon</td>
        <td>The new song</td>
        <td>1991</td>
        <td>No</td>
      </tr>
      <tr>
        <td>Cloudies</td>
        <td>Fly with me</td>
        <td>1986</td>
        <td>Yes</td>
      </tr>
    </tbody>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...