Welcome to OGeek Q&A 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?


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

1 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...