javascript - jquery find specific columns in a table column in tbody element - Stack Overflow

var html_table ="<table class='table'>" +"<thead>" +"<

var html_table =
    "<table class='table'>" +
    "<thead>" +
    "<tr><th>#</th><th>First</th><th>Second</th><th>Third</th><th>Fourth</th><th>Fifth</th></tr></thead>" +
    "<tbody>" +
    "<tr><td ></td><td></td><td>Pitt</td><td>35</td><td>New York</td><td>USA</td></tr>" +
    "</tbody>" +
    "</table>";

var $html_table = $(html_table);
var first_column= $html_table.find('???');
var second_column= $html_table.find('???');

So i have above table in javascript and using jquery to get the first and third columns. But find() method doesn't seem to be flexible enough to get first and third column inside tbody element

var html_table =
    "<table class='table'>" +
    "<thead>" +
    "<tr><th>#</th><th>First</th><th>Second</th><th>Third</th><th>Fourth</th><th>Fifth</th></tr></thead>" +
    "<tbody>" +
    "<tr><td ></td><td></td><td>Pitt</td><td>35</td><td>New York</td><td>USA</td></tr>" +
    "</tbody>" +
    "</table>";

var $html_table = $(html_table);
var first_column= $html_table.find('???');
var second_column= $html_table.find('???');

So i have above table in javascript and using jquery to get the first and third columns. But find() method doesn't seem to be flexible enough to get first and third column inside tbody element

Share asked Aug 10, 2016 at 20:01 josh_boazjosh_boaz 2,0237 gold badges35 silver badges74 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

You can get the column using .eq function.

$html_table.find('tbody tr td').eq(0) // First element
$html_table.find('tbody tr td').eq(2) // third element

In eq function, use the index, that starting with 0.

You can get access to all td of column with next code:

var columnNumber = 0; //first column
$.each($html_table.find("tr"), function(){
  var tdOfCurrentColumn = $(this).children().eq(columnNumber);
})

Let's say your table has id="table". You can do this:

var first_column = $('#table:first-child');
var second_column = $('#table:nth-child(2)');

I haven't tried this out, but it should work. Feel free to utilize css3 selectors in all their magnificent glory.

From Chris, I think it is easier using the CSS3 selectors.

var first_column= $("tbody td:nth-child(1)",$html_table)
var second_column=  $("tbody td:nth-child(2)",$html_table)

check this out. https://jsfiddle/nvg4f2at/1/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742402647a4437221.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信