How to obtain only visible elements inside an HTML table using jQuery?

最后都变了- 提交于 2021-02-10 04:16:31

问题


I have the following problem: I have a table in which each row has some cells that are visible, and some that aren't. Something like this:

<table>
  <thead>
  </thead>
  <tbody>
    <tr>
      <td id='cell_a1'>A</td>
      <td id='cell_b1' style='display:none'>B</td>
    </tr>
    <tr>
      <td id='cell_a2'>C</td>
      <td id='cell_b2' style='display:none'>D</td>
    </tr>
  </tbody>
</table>`

And I need to retrieve only the table's visible content using the .html() method, like this for the table above:

<table>
  <thead>
  </thead>
  <tbody>
    <tr>
      <td id='cell_a1'>A</td>
    </tr>
    <tr>
      <td id='cell_a2'>C</td>
    </tr>
  </tbody>
</table>`

I tried using the visible selector, but I might have used it the wrong way because I couldn't make it work. Anyway, any help is appreciated.


回答1:


To get all visible elements, you can use the :visible selector with this syntax :

$('td:visible')

But this won't enable you to get the html for the all table as if it didn't contain the hidden elements.

For that, you could temporarily duplicate the table and remove the not visible cells :

var t = $('table').clone();
t.appendTo(document.body);
t.find('td').not(':visible').remove();
var html = t.html();
t.remove();

Demonstration (open the console)




回答2:


This is late I know, but since I like learning ... ;-)

At jQuery :visible Selector, there's a nice example.

HTML:

<table>
...
</table>

<div id="output"></div>

JS:

var t = $('table').clone();
$('td', t).filter(function() { return $(this).css('display') == 'none'; }).remove();
var html = t.html();
$('#output').text(html); // This shows the HTML code

See JSFiddle



来源:https://stackoverflow.com/questions/14237927/how-to-obtain-only-visible-elements-inside-an-html-table-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!