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.

    Try Teams for free Explore Teams
  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 13 years, 1 month ago Modified 2 years ago Viewed 106k 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 Improve this question Follow edited Dec 29, 2018 at 7:18 Cœur's user avatar Cœur 38.5k26 gold badges202 silver badges275 bronze badges asked Oct 13, 2011 at 12:20 Random Guy's user avatar Random GuyRandom Guy 2,9105 gold badges22 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) 45

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 Improve this answer Follow edited Nov 23, 2022 at 16:04 Andrei Cleland's user avatar Andrei Cleland 4365 silver badges11 bronze badges answered Oct 13, 2011 at 12:41 Eineki's user avatar EinekiEineki 14.9k6 gold badges53 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
  • 2 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 Improve this answer 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 7,00132 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 | 3

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 Improve this answer Follow edited Sep 7, 2022 at 14:01 Matt Sephton's user avatar Matt Sephton 4,0724 gold badges38 silver badges47 bronze badges answered May 30, 2022 at 21:14 Dr4v's user avatar Dr4vDr4v 3853 silver badges7 bronze badges 2
  • 1 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 Improve this answer Follow answered May 6, 2013 at 22:59 Doug's user avatar DougDoug 6,97712 gold badges80 silver badges115 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
  • We'll Be In Touch - A New Podcast From Stack Overflow!
  • The app that fights for your data privacy rights
  • Featured on Meta
  • More network sites to see advertising test
  • We’re (finally!) going to the cloud!
  • Call for testers for an early access release of a Stack Overflow extension...
Visit chat

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

  • Are Quantum Algorithms better than classical algorithms for all problems?
  • Testing Puzzles for Puzzle Book: Enigmatic Puzzle
  • Is there a theorem in metaphysics that basically says, "Biting the bullet will be inevitable in any metaphysical theory?"
  • How does the Warlock's invocation Gaze of Two Minds interact with a creature with the Invisible Condition?
  • Suggestion for catching a flight with short layover in Amsterdam
  • What is the origin of the term "Dog Character" in the context of fighting games?
  • Why the second C in "recyceln" is pronounced [k] instead of [ts]?
  • How to handle a campaign where the players are trapped inside a monster controlled by another player?
  • Accused of violating NDA on thesis
  • What is the basis for the view of Oneness in Theravada?
  • Bleeding radiators
  • Does a touch spell have advantage when delivered by an invisible Familiar?
  • How to DSolve[{-0.8*y'[x]*y''[x]/(1 + (y'[x])^2)^1.4 == 0.77781490, y[0] == 0, y[1] == 1}, y[x], x]
  • Did Superdana manufacture a 66 AC outlet power strip/surge protector?
  • Gifting $10k to my 17 year old nephew
  • How should I go about handling multiple phone resolutions from a reference resolution?
  • The Talking Dog's Treats
  • What is the Calvinist/Reformed solution to the Problem of Hell?
  • Where in the Gospels does Jesus explain what 'The Truth' is?
  • Commencement and repeal dates in UK Acts of Parliament - meaning of "From and after"
  • Brushing pastries with jam
  • Does the twin paradox hold in a universe that's empty except for the twins?
  • Dantzig-Wolfe Decomposition for nurse Scheduling problem
  • Why does glm in R with family binomial(link="log") sometimes require start values?
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