Loop through the 1st row of HTML table (GridView) and get the cell content using Javascript

问题: I have a GridView which reads from a file and when I inspect element its HTML table looks something like this : <div> <table> <tbody>...

问题:

I have a GridView which reads from a file and when I inspect element its HTML table looks something like this :

<div>
<table>
  <tbody>
     <tr>
       <th id= "header1">...</th>
       <th id= "header2">...</th>
       <th id= "header3">...</th>
       <th id= "header4">...</th>
       <th id= "header5">...</th>
      <tr>..</tr>
      <tr>..</tr>
      <tr>..</tr>
      <tr>..</tr>
   </table>
</div>

I need to loop through the first row to be able to get the header values using javascript. I can't seem to loop through just the first row to extract values.

I understand that I should count the number of columns first to create my "for" loop but I am only able to count my rows.

var table = document.getElementById("table1");
var rowCount = table.rows.length;
for (var r = 0, n = table.rows.length; r < n; r++) {

There's nothing like table.columns.length.How do I do that? Any help would be greatly appreciated.


回答1:

like that you will get header values in an array

const el = [...document.querySelectorAll("th")];

const res = el.map(el => el.innerHTML)

console.log(res)
<div>
  <table>
    <tbody>
      <tr>
        <th id="header1">TEXT1</th>
        <th id="header2">TEX2</th>
        <th id="header3">TEXT3</th>
        <th id="header4">TEXT4</th>
        <th id="header5">TEXT5</th>
      </tr>
      <tr>..</tr>
      <tr>..</tr>
      <tr>..</tr>
      <tr>..</tr>
  </table>
</div>

  • 发表于 2019-03-09 00:21
  • 阅读 ( 182 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除