Javascript使用tr类获取多个tds的文本节点

时间:2018-08-01 08:57:19

标签: javascript html class innerhtml tr

该问题与我在此处发布的第一个问题有些相关:Javascript to get text node of td using tr class 我在下面有以下代码:

<table>
  ...
[Multiple div lines ommited for brevity]

<tr class="bibItemsEntry"> 
<td width="31%" ><!-- field 1 -->&nbsp;Archives, Thesis Col. Graduate, 12F (Mezz.) Henry Sy Sr. Hall 
</td>
<td width="46%" ><!-- field C -->&nbsp;<a href="/search~S1?/cCDTG006829/ccdtg006829/-3,-1,,E/browse">CDTG006829</a> <!-- field v --><!-- field # -->&nbsp;<!-- field ! -->&nbsp;ROOM USE ONLY</td>
<td width="23%" ><!-- field % -->&nbsp;CHECK SHELF </td></tr>
</table>

<p id="demo">Test</p>

[multiple divs <tr>s <td>s omitted for brevity]
....
<tr  class="bibItemsEntry">

<td width="31%" ><!-- field 1 -->&nbsp;Shelf 194, 10F Mezzanine (Filipiniana), Henry Sy Sr. Hall 
</td>
<td width="46%" ><!-- field C -->&nbsp;<a href="/search~S1?/cPS3568.O5333+A6+2016/cps+3568+o5333+a6+2016/-3,-1,,E/browse">PS3568.O5333 A6 2016</a> <!-- field v --><!-- field # -->&nbsp;<!-- field ! -->&nbsp;ROOM USE ONLY</td>
<td width="23%" ><!-- field % -->&nbsp;LIB USE ONLY </td></tr>
</table>
<p id="demo">Test</p>

我想做的是使用javascript并获取<td><tr class="bibItemsEntry">的文本节点每次出现的第一个值,并将其放入p id = demo(即分别放入s)。我正在尝试将值放入<p id="demo">中。 我正在尝试以下javascript代码:

var x = document.getElementsByClassName("bibItemsEntry");
document.getElementById("demo").innerHTML = x[0].innerHTML;

[benvc][1] answered the below code, thanks to him/her: 
const td = document.querySelector('.bibItemsEntry td:first-child');
const p = document.getElementById('demo');
p.innerHTML = td.textContent;
  

它只会得到足够真实的第一次迭代,我无法在第一个问题中提到它……谢谢!!

1 个答案:

答案 0 :(得分:0)

您需要像这样循环遍历x结果:

var x = document.getElementsByClassName("bibItemsEntry");

[].forEach.call(x, function(item) {
  var demo = item.querySelector('.demo');
  var firstTd = item.querySelector('td:first-child');

  demo.textContent = firstTd.textContent;
});
<table id="codexpl" border="1">
  <tr>
    <th>#</th>
    <th>Text</th>
    <th>Demo</th>
  </tr>
  <tr class="bibItemsEntry">
    <td width="31%">
      <!-- field 1 -->&nbsp;Archives, Thesis Col. Graduate, 12F (Mezz.) Henry Sy Sr. Hall
    </td>
    <td width="46%">
      <!-- field C -->&nbsp;<a href="/search~S1?/cCDTG006829/ccdtg006829/-3,-1,,E/browse">CDTG006829</a>
      <!-- field v -->
      <!-- field # -->&nbsp;
      <!-- field ! -->&nbsp;ROOM USE ONLY</td>
    <td>
      <p class="demo"></p>
    </td>
  </tr>
  <tr class="bibItemsEntry">
    <td width="31%">
      <!-- field 1 -->&nbsp;Shelf 194, 10F Mezzanine (Filipiniana), Henry Sy Sr. Hall
    </td>
    <td width="46%">
      <!-- field C -->&nbsp;<a href="/search~S1?/cPS3568.O5333+A6+2016/cps+3568+o5333+a6+2016/-3,-1,,E/browse">PS3568.O5333 A6 2016</a>
      <!-- field v -->
      <!-- field # -->&nbsp;
      <!-- field ! -->&nbsp;ROOM USE ONLY</td>
    <td>
      <p class="demo"></p>
    </td>
  </tr>
</table>
<div id="demo"></div>