Hiding Columns In Table JavaScript - Html - Stack Overflow

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Explore Teams Create a free Team
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs Hiding columns in table JavaScript Ask Question Asked 12 years, 8 months ago Modified 1 year, 7 months ago Viewed 104k times 22

This script stops working the moment I add a table inside a table, so how to get it worked? I don't need any jQuery solutions, I want pure JavaScript. Here's my script found on the Internet:

<script> function show_hide_column(col_no, do_show) { var stl; if (do_show) stl = 'block' else stl = 'none'; var tbl = document.getElementById('id_of_table'); var rows = tbl.getElementsByTagName('tr'); for (var row=1; row<rows.length;row++) { var cels = rows[row].getElementsByTagName('td') cels[col_no].style.display=stl; } } </script>

Here's my HTML:

<table id='id_of_table' border=1> <tr><td colspan="4"><table><tr><td></td></tr></table></td></tr> <tr><td> 2</td><td> two</td><td> deux</td><td> zwei</td></tr> <tr><td> 3</td><td> three</td><td> trois</td><td> drei</td></tr> <tr><td> 4</td><td> four</td><td>quattre</td><td> vier</td></tr> <tr><td> 5</td><td> five</td><td> cinq</td><td>f&uuml;nf</td></tr> <tr><td> 6</td><td> six</td><td> six</td><td> sechs</td></tr> </table>

And here's my Form:

<form> Enter column no: <input type='text' name=col_no><br> <input type='button' onClick='javascript:show_hide_column(col_no.value, true);' value='show'> <input type='button' onClick='javascript:show_hide_column(col_no.value, false);' value='hide'> </form> Share Follow edited Dec 29, 2018 at 7:18 Cœur's user avatar Cœur 38.2k26 gold badges201 silver badges274 bronze badges asked Oct 13, 2011 at 12:20 Random Guy's user avatar Random GuyRandom Guy 2,9005 gold badges21 silver badges33 bronze badges 4
  • Han and Jabba now collaberate on a script language :) en.wikipedia.org/wiki/Jabba_the_Hutt – Mark Schultheiss Commented Oct 13, 2011 at 12:22
  • 1 just as a sidenote: if you need to have nested tables, it seems like you have bigger problems than a not-working javascript snippet. don't use tables for layout: hotdesign.com/seybold – oezi Commented Oct 13, 2011 at 12:23
  • Ya, nested tables is causing problems, I know i can work around with a JavaScript but tweaking in Script can be possible... – Random Guy Commented Oct 13, 2011 at 12:25
  • JabbaScript for the win! schnell.net/jabbascript.html – avall Commented Oct 13, 2011 at 12:36
Add a comment |

4 Answers 4

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 44

You can leverage the col tag and then the solution is straightforward using only vanilla JavaScript. The col tag has only a few CSS attributes, but visibility is one of them:

function show_hide_column( col_no, do_show ){ const table = document.getElementById( 'id_of_table' ) const column = table.getElementsByTagName( 'col' )[col_no] if ( column ){ column.style.visibility = do_show?"":"collapse"; } } const btnHide = document.getElementById( 'btnHide' ) btnHide.addEventListener( "click", () => show_hide_column( 2, false )) const btnShow = document.getElementById( 'btnShow' ) btnShow.addEventListener( "click", () => show_hide_column( 2, true )) <table id='id_of_table' border=1> <col class="col1"/> <col class="col2"/> <col class="col3"/> <col class="col4"/> <tr><td colspan="4"><table><tr><td></td></tr></table></td></tr> <tr><td> 2</td><td> two</td><td> deux</td><td> zwei</td></tr> <tr><td> 3</td><td> three</td><td> trois</td><td> drei</td></tr> <tr><td> 4</td><td> four</td><td>quattre</td><td> vier</td></tr> <tr><td> 5</td><td> five</td><td> cinq</td><td>fÜnf</td></tr> <tr><td> 6</td><td> six</td><td> six</td><td> sechs</td></tr> </table> <button id="btnHide">hide French</button> <button id="btnShow">show French</button>

References:

  • col
  • visibility on quirksmode
Share Follow edited Nov 23, 2022 at 16:04 Andrei Cleland's user avatar Andrei Cleland 4164 silver badges11 bronze badges answered Oct 13, 2011 at 12:41 Eineki's user avatar EinekiEineki 14.9k6 gold badges52 silver badges60 bronze badges 7
  • 3 +1, nice! I didn't even know the col tag... Learn something every day. :-) – Peter-Paul van Gemerden Commented Oct 13, 2011 at 13:08
  • 10 Was hoping to use that as well, as I have a table with <col> elements, but for some reason in Chrome setting visibility = collapse does not work for me :( – Vlad Commented Mar 14, 2013 at 3:58
  • 5 Such a shame that this doesn't seem to work universally as this is the perfect solution - it's exactly what <col> is for. Firefox is ok but it doesn't work in WebKit-based browsers (I tested chrome and safari) – WickyNilliams Commented Mar 3, 2014 at 17:23
  • 4 If you'd like this to work in Google Chrome, please vote for the bug at bugs.chromium.org/p/chromium/issues/detail?id=174167 – Colonel Panic Commented Dec 31, 2016 at 16:13
  • 1 When you hide a column, the space gained isn't given to the remaining columns. – WinEunuuchs2Unix Commented Apr 17, 2022 at 2:58
| Show 2 more comments 10

You could use children and check their tagName to make sure they're td's. Something like this:

function show_hide_column(col_no, do_show) { var tbl = document.getElementById('id_of_table'); var rows = tbl.getElementsByTagName('tr'); for (var row = 0; row < rows.length; row++) { var cols = rows[row].children; if (col_no >= 0 && col_no < cols.length) { var cell = cols[col_no]; if (cell.tagName == 'TD') cell.style.display = do_show ? 'block' : 'none'; } } }

Edit: Here's a working example: http://jsfiddle.net/3DjhL/2/.

Edit: In fact, I've just remembered the rows and cols properties, which make it even simpler. See http://jsfiddle.net/3DjhL/4/ to see it in action.

function show_hide_column(col_no, do_show) { var rows = document.getElementById('id_of_table').rows; for (var row = 0; row < rows.length; row++) { var cols = rows[row].cells; if (col_no >= 0 && col_no < cols.length) { cols[col_no].style.display = do_show ? '' : 'none'; } } }

Oh, and if you think the column numbers should start at 1 (which they don't), you'll have to offset that somewhere. For example at the top of show_hide_column():

col_no = col_no - 1; Share Follow edited Oct 13, 2011 at 14:00 answered Oct 13, 2011 at 12:31 Peter-Paul van Gemerden's user avatar Peter-Paul van GemerdenPeter-Paul van Gemerden 6,99131 silver badges37 bronze badges 3
  • nah, doesn't hide any columns for me – Random Guy Commented Oct 13, 2011 at 12:35
  • Your problem is that getElementsByTagName returns all the so-named descendants of the element in question, not just the immediate child nodes with that name. Your script is likely throwing an "array out of bounds" error on cels[col_no].style.display=stl;. Following @PPvG's lead is your best bet. – Ishmael Commented Oct 13, 2011 at 12:53
  • @V413HAV my apologies, I'd made a (small) mistake. I did say "something like this", not "exactly this", but I digress. It works now, as you can see in the jsFiddle. – Peter-Paul van Gemerden Commented Oct 13, 2011 at 13:06
Add a comment | 2

The important thing here is the selector, it could be vanilla or jquery:

document.querySelectorAll('#yourtable tbody tr td:nth-child(1)').forEach(el=>el.style.display = 'none')

From the code above, the nth-child(1) selector has a 1-based index, there you define the column you want to hide ;)

Share Follow edited Sep 7, 2022 at 14:01 Matt Sephton's user avatar Matt Sephton 3,9404 gold badges36 silver badges47 bronze badges answered May 30, 2022 at 21:14 Dr4v's user avatar Dr4vDr4v 3763 silver badges6 bronze badges 2
  • The only issue with here is that the code above will not hide the column header. To do that you will need to add document.querySelectorAll("#yourtable tbody tr td:nth-child(1)").forEach(el => el.style.display = 'none') with the code above. – Joshua Commented Dec 19, 2022 at 21:08
  • @Joshua you referenced td in your code again. In my case that was not enough and I had to use th like this: '#yourtable thead tr th:nth-child(1)' (for table header) and '#yourtable tfoot tr th:nth-child(1)' (for footer) – abu Commented Apr 15 at 7:30
Add a comment | 1

I had a situation where it would have been a very big hassle to modify every single TD value and add the appropriate class name so I could toggle it. As a result I wrote some JavaScript to do that automatically. Please see the following code.

tbl = document.getElementById("Mytable") classes = getClasses(tbl.rows[0]); setClasses(tbl, classes); toggleCol("col0"); toggleCol("col1"); function getClasses(row){ var cn = 0; var classes = new Array(); for(x=0; x < row.cells.length; x++){ var cell = row.cells[x]; var c = new Column(cell.textContent.trim(), cell.offsetLeft, cell.offsetLeft + cell.offsetWidth, x); classes[x]= c; } return classes; } function Column(name, left, right, cols) { this.name = name; this.left = left; this.right = right; this.cols = cols; } function setClasses(table, classes){ var rowSpans = new Array(); for(x=0; x < table.rows.length; x++){ var row = table.rows[x]; for(y=0; y < row.cells.length; y++){ var cell = row.cells[y]; for(z=0; z < classes.length; z++){ if(cell.offsetLeft >= classes[z].left && cell.offsetLeft <= classes[z].right){ cell.className = "col" + classes[z].cols; } } } } } function toggleCol(name){ var cols = document.getElementsByClassName(name); for(x=0; x < cols.length; x++){ cols[x].style.display= (cols[x].style.display == 'none') ? '' : 'none'; } }

In my example I take a look at the first row to set the top level header (In my example I had several who had colspans). It uses the offsetLeft and offsetWidth to determine the range of the top header (which in my cases has sub headers), so that all sub-columns would toggle with its parent.

Based on these values setClasses sets the appropriate classes to all the elements.

In my example I then toggle "col0" and "col1", so they would be invisible (Running the function again would make them visible again).

Share Follow answered May 6, 2013 at 22:59 Doug's user avatar DougDoug 6,85711 gold badges80 silver badges114 bronze badges Add a comment |

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved Draft discarded

Sign up or log in

Sign up using Google Sign up using Email and Password Submit

Post as a guest

Name Email

Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • The Overflow Blog
  • How to build open source apps in a highly regulated industry
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • What makes a homepage useful for logged-in users
  • The [lib] tag is being burninated

Linked

0 Trying to have the option to hide the details column on the page 4 Activeadmin - user option for hide and unhide column -1 Hide table column based on TD id 1 Add and remove a class to a collection of items on button click (vanilla JS) 1 How do I show/hide an entire column when a button is clicked? 0 Auto hide Table Content By Default 0 Hiding HTML table columns with JavaScript 1 Hide/Show Table Columns with Javascript (fix for all browsers?) 1 Javascript: Hiding table rows 2 Hide columns in HTML table via CSS 1 Table in Javascript - hide/show columns 2 Hide a table column with Javascript 3 Hide HTML Table Columns 0 jQuery hiding columns on different tables 0 JQuery - Hide Table Columns 1 Displaying/Hiding table data using JavaScript

Hot Network Questions

  • Name this kimberling center
  • Measure by mass vs. 'Spooned and Leveled'
  • Are there any parts of the US Constitution that state that the laws apply universally to all citizens?
  • What does a letter "R" means in a helipad?
  • I can't mount my external hard drive in Linux
  • Why should I meet my advisor even if I have nothing to report?
  • Why are my star jasmine flowers turning brown
  • How much time do I need on my Passport expiry date to leave Australia for South Africa?
  • Turning Misty step into a reaction to dodge spells/attacks
  • Do we know a lower bound or the exact number of 3-way races in France's 2nd round of elections in 2024?
  • I want to leave my current job during probation but I don't want to tell the next interviewer I am currently working
  • Why didn't Jimmy Neutron realize immediately when he read the note on the refrigerator that the note is phony, as the note says "son or daughter..."?
  • Why can't LaTeX (seem to?) Support Arbitrary Text Sizes?
  • common.apex.runtime.impl.ExecutionException: Unrecognized base64 character: [
  • Is arXiv strictly for new stuff?
  • Staying in USA longer than 3 months
  • Line from Song KÄMPFERHERZ
  • Does concentrating on a different spell end a concentration spell?
  • A chess engine in Java: generating white pawn moves - take II
  • How does this switch work on each press?
  • Why does Paul's fight with Feyd-Rautha take so long?
  • Book in 90's (?) about rewriting your own genetic code
  • How to maintain dependencies shared among microservices?
  • Who originated the idea that the purpose of government is to protect its citizens?
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

default

Từ khóa » Html Table Hide Column Javascript