Skip to content Skip to sidebar Skip to footer

How To Hide A Table Row In Html Here The Condition As Row Values Using Javascript ? If Two Row Values Are The Same Then Hide One

I have a html table where I need to hide one row where column value is same. like if key1 and key2 have same value then hide one row. here each row is different, in that there

Solution 1:

You can loop over all rows, save found values in an array and if a value is already in an array you will hide it instead.

var rows = document.querySelectorAll('table tr');
var foundValues = [];
rows.forEach(function(el){
  console.log(foundValues);
  console.log(el.children[1].innerHTML);
  if(foundValues.includes(el.children[1].innerHTML)) {
    el.style.display = 'none';
  }
  else {
    foundValues.push(el.children[1].innerHTML);
  }
});
<table><tr><td>Key1</td><td>Value1</td></tr><tr><td>Key2</td><td>Value2</td></tr><tr><td>Key3</td><td>Value2</td></tr><tr><td>Key4</td><td>Value4</td></tr></table>

Solution 2:

Assuming the value will always be in the second field of each row I have a solution here which should work.

//we need to check that the window has loaded so we can target the elements in the DOM.window.onload = function(){
  var seen = [];  
  var tableRows = document.getElementsByTagName('tr');
  for(i = 0; i < tableRows.length; i++){
    //get the table data for this particular table rowvar tableData = tableRows[i].getElementsByTagName('td');
    //the value will be contained in the second td tag of the row so we retrieve it as follows:var value = tableData[1].innerText;
    //log the value to check.console.log(value);    

    if(seen[value]){
      //if the value already exists hide the table row that contains this value.
      tableRows[i].style.display = "none"; 
    }else{
      //add the value to the 'seen' array.
      seen[value] = true;
    }
  }

}

You can test this with the following table where two values are the same.

<!DOCTYPE html><html><head><title>Hide test</title><script>//javascript code goes here</script></head><body><table><tr><td>Key1</td><td>Value1</td></tr><tr><td>Key2</td><td>Value2</td></tr><tr><td>Key3</td><td>Value1</td></tr></table></body></html>

Post a Comment for "How To Hide A Table Row In Html Here The Condition As Row Values Using Javascript ? If Two Row Values Are The Same Then Hide One"