最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Hide column table by document.getElementsByTagName('table') - Stack Overflow

programmeradmin4浏览0评论

i use the following code to print a table. i dont know how to hide the last two columns before sending to print. thanks for the support. i am not very good i need an example. can anyone help me? thank you..

<script type="text/javascript">
function printPage(){
    var tableData = '<table border="1" style="border-collapse:collapse; background-color: lightblue;font-size: large;">'+document.getElementsByTagName('table')[0].innerHTML+'</table>';
    var t='Tabella configurazione slot giorni e ore. &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;';
    var data = '<button onclick="window.print()">Print this page</button>'+tableData;   
    
    myWindow=window.open('','','width=800,height=600,left=300,top=100');
        myWindow.innerWidth = screen.width;
        myWindow.innerHeight = screen.height;
        myWindow.screenX = 0;
        myWindow.screenY = 0;
        myWindow.document.write(data);
        myWindow.focus();
    };
</script>

i use the following code to print a table. i dont know how to hide the last two columns before sending to print. thanks for the support. i am not very good i need an example. can anyone help me? thank you..

<script type="text/javascript">
function printPage(){
    var tableData = '<table border="1" style="border-collapse:collapse; background-color: lightblue;font-size: large;">'+document.getElementsByTagName('table')[0].innerHTML+'</table>';
    var t='Tabella configurazione slot giorni e ore. &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;';
    var data = '<button onclick="window.print()">Print this page</button>'+tableData;   
    
    myWindow=window.open('','','width=800,height=600,left=300,top=100');
        myWindow.innerWidth = screen.width;
        myWindow.innerHeight = screen.height;
        myWindow.screenX = 0;
        myWindow.screenY = 0;
        myWindow.document.write(data);
        myWindow.focus();
    };
</script>
Share Improve this question asked Mar 19 at 16:40 isaisa 51 silver badge1 bronze badge 1
  • 5 Rather than using JS for this, I strongly suggest you consider using print-friendly CSS techniques to set the formatting and the content of what you want to be visible in the printed version - see developer.mozilla./en-US/docs/Web/CSS/CSS_media_queries/… for details – ADyson Commented Mar 19 at 16:42
Add a comment  | 

2 Answers 2

Reset to default 2

This is a way to do it:

<script type="text/javascript">
function printPage(){
    var tableData = '<table border="1" style="border-collapse:collapse; background-color: lightblue;font-size: large;">'+document.getElementsByTagName('table')[0].innerHTML+'</table>';
    var t='Tabella configurazione slot giorni e ore. &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;';
    var data = '<button onclick="window.print()">Print this page</button>'+tableData;
    var script = `
        <script>
            window.addEventListener("load", function() {
                let tableRows = document.querySelectAll("table tr");
                for (let tr of tableRows) {
                    let tds = tr.children;
                    tds[tds.length - 2].style.display = "none";
                    tds[tds.length - 1].style.display = "none";
                }
            });
        </script>
    `;
    
    myWindow=window.open('','','width=800,height=600,left=300,top=100');
        myWindow.innerWidth = screen.width;
        myWindow.innerHeight = screen.height;
        myWindow.screenX = 0;
        myWindow.screenY = 0;
        myWindow.document.write(data + script);
        myWindow.focus();
    };
</script>

Basically I'm setting the last two td elements of all rows to have a display none attribute which will hide them.

Three Solutions

Solution 1 is hard coded to remove the last two columns of a <table>. Both solutions use an <frame> to print instead of a window. Solution 2 accepts an array of indices that corresponds to the <table> columns for removal. If nothing is passed the whole <table> will be printed. For example:

/* Solution 2 */
printPage([2, 3]) // Remove 3rd & 4th columns
printPage([0])    // Remove first column
printPage()       // No columns to remove  

Solution 3 is Solution 2 that prints a window instead of an <iframe>.

Solution 1

The following example has a <table>. The function printPage() runs and creates an htmlString containing:

  • a <style>
  • a <main> with the dimensions of a 8.5 x 11 paper
  • a <table> that has all of the original <table> content.

a <iframe> and a <button> is appended to the <body>, then the htmlString is assigned to the <iframe> [srcdoc] attribute which then renders as HTML within the <iframe>. Note, the <table> within the <iframe> is missing the last two columns. The reason why is because the <style> within the <iframe> has the following ruleset:

table tr th:nth-last-child(-n+2),
table tr td:nth-last-child(-n+2) {
  display: none;
}

The print button in the example will not work on SO, for a completely functioning example see this CodePen

const printPage = () => {
  const htmlStr = `
  <style>
    main {
      width: 816px;
      height: 1056px;
    }
    table {
      border-collapse: collapse;
      border: 1px solid #000;
      background-color: lightblue;
      font-size: large;
    }
    table tr th:nth-last-child(-n+2),
    table tr td:nth-last-child(-n+2) {
      display: none;
    }
    td, 
    th {
      border: 1px solid #000;
    }
  </style>
  <main>
    <table>${ document.querySelector("table").innerHTML}</table>
  </main>`;
  const iframe = document.createElement("iframe");
  iframe.name = "printFrame";
  iframe.setAttribute("width", "816");
  iframe.setAttribute("height", "1056");
  iframe.srcdoc = htmlStr;
  document.body.append(iframe);
  iframe.insertAdjacentHTML("beforebegin", `<button onclick="frames['printFrame'].print()" display:block">Print this page</button>`);
  frames["printFrame"].focus();
};

printPage();
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A1</td>
      <td>B1</td>
      <td>C1</td>
      <td>D1</td>
    </tr>
    <tr>
      <td>A2</td>
      <td>B2</td>
      <td>C2</td>
      <td>D2</td>
    </tr>
    <tr>
      <td>A3</td>
      <td>B3</td>
      <td>C3</td>
      <td>D3</td>
    </tr>
    <tr>
      <td>A4</td>
      <td>B4</td>
      <td>C4</td>
      <td>D4</td>
    </tr>
  </tbody>
</table>

Solution 2

Solution 2 is simular to Solution 1 in that it relies on CSS. A <colgroup> is added to the original <table> and a <col> is added to the <colgroup> for each column of <table>. An array of indices can be passed which indicates which columns to remove for printing. Each <col> designated for removal is given the .collapse class:

.collapse {
  visibility: collapse;
}

This particular style will remove an entire column if assigned to a <col>.

The print button in the example will not work on SO, for a completely functioning example see this CodePen

const printPage = (array = []) => {
  let colQty = 0;
  const colArray = [];
  const table = document.querySelector("table");
  const colGrp = document.createElement("colgroup");
  table.prepend(colGrp);
  colQty = table.rows[0].cells.length;
  for (let c = 0; c < colQty; c++) {
    const col = document.createElement("col");
    colArray.push(col);
    colGrp.append(col);
  }
  array.forEach(colIdx => colArray[colIdx].className = "collapse");
  const htmlStr = `
  <style>
    main {
      width: 816px;
      height: 1056px;
    }
    table {
      border-collapse: collapse;
      border: 1px solid #000;
      background-color: lightblue;
      font-size: large;
    }
    td, 
    th {
      border: 1px solid #000;
    }
    .collapse {
      visibility: collapse;
    }
  </style>
  <main>
    <table>${table.innerHTML}</table>
  </main>`;
  const iframe = document.createElement("iframe");
  iframe.name = "printFrame";
  iframe.setAttribute("width", "816");
  iframe.setAttribute("height", "1056");
  iframe.srcdoc = htmlStr;
  document.body.append(iframe);
  iframe.insertAdjacentHTML("beforebegin", `<button onclick="frames['printFrame'].print()">Print this page</button>`);
  frames["printFrame"].focus();
};

const removeLastTwo = [2, 3];

printPage(removeLastTwo);
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A1</td>
      <td>B1</td>
      <td>C1</td>
      <td>D1</td>
    </tr>
    <tr>
      <td>A2</td>
      <td>B2</td>
      <td>C2</td>
      <td>D2</td>
    </tr>
    <tr>
      <td>A3</td>
      <td>B3</td>
      <td>C3</td>
      <td>D3</td>
    </tr>
    <tr>
      <td>A4</td>
      <td>B4</td>
      <td>C4</td>
      <td>D4</td>
    </tr>
  </tbody>
</table>

Solution 3

Solution 3 is Solution 2 that prints in a window instead of am <iframe>. Opening a new window is blocked by SO, for a completely functioning example see this CodePen

const printPage = (array = []) => {
 let colQty = 0;
 const colArray = [];
 const table = document.querySelector("table");
 const colGrp = document.createElement("colgroup");
 table.prepend(colGrp);
 colQty = table.rows[0].cells.length;
 for (let c = 0; c < colQty; c++) {
  const col = document.createElement("col");
  colArray.push(col);
  colGrp.append(col);
 }
 array.forEach((colIdx) => (colArray[colIdx].className = "collapse"));
 const htmlStr = `
  <style>
    main {
      width: 816px;
      height: 1056px;
    }
    table {
      border-collapse: collapse;
      border: 1px solid #000;
      background-color: lightblue;
      font-size: large;
    }
    td, 
    th {
      border: 1px solid #000;
    }
    .collapse {
      visibility: collapse;
    }
    @media print {
      button {
        display: none;
      }
    }
  </style>
  <main>
    <button onclick="window.print()" style="display:block;">Print this page</button>
    <table>${table.innerHTML}</table>
  </main>`;
 win = window.open("", "", (width = "816"), (height = "1056"));
 win.document.write(htmlStr);
 win.document.close();
 win.focus();
};

const removeLastTwo = [2, 3];

printPage(removeLastTwo);
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A1</td>
      <td>B1</td>
      <td>C1</td>
      <td>D1</td>
    </tr>
    <tr>
      <td>A2</td>
      <td>B2</td>
      <td>C2</td>
      <td>D2</td>
    </tr>
    <tr>
      <td>A3</td>
      <td>B3</td>
      <td>C3</td>
      <td>D3</td>
    </tr>
    <tr>
      <td>A4</td>
      <td>B4</td>
      <td>C4</td>
      <td>D4</td>
    </tr>
  </tbody>
</table>

发布评论

评论列表(0)

  1. 暂无评论