Javascript:按类名查找标记中元素的值

时间:2018-03-22 00:18:44

标签: javascript html

我有以下代码:

H{count,a} = M;

更新 我正在遍历表行以获取<tr style="background: rgb(243, 236, 236);"> <td style="width:20%;">1:0</td> <td style="width:70%;"><span><i class="glyphicon glyphicon-random"></i></span><span class="Pattern">Geometric Decomposition</span></td> <td style="width:10%;">1</td> </tr> <tr> <td style="width:20%;">1:11</td> <td style="width:70%;"><span><i class="glyphicon glyphicon-road"></i></span><span class="Pattern">Pipeline</span></td> <td style="width:10%;">1</td> </tr> 中的值,同时还读取第一个单元格的值(ID,例如class="Pattern")。我目前的javascript代码:

1:01

但是 nodeIds = [] nodePatterns = [] for(i = 0; i < tds.length; ++i) { var cells = tds[i].getElementsByTagName("td"); nodeIds.push(cells[0].innerHTML); nodePatterns.push(cells[1].innerHTML); } 我得到以下值:

  1. cells[1].innerHTML
  2. <span><i class="glyphicon glyphicon-random"></i></span><span class="Pattern">Geometric Decomposition</span>
    现在我正在寻找一种方法来获取标记<span><i class="glyphicon glyphicon-road"></i></span><span class="Pattern">Pipeline</span>的值span,即几何分解和管道。我可以使用像class="Pattern"这样的javascript函数...但我正在寻找一种更优雅的方法来通过调用带有标记名称的标记来解决这个问题。
    是他们的一种方式吗?

2 个答案:

答案 0 :(得分:4)

document.querySelector('.pattern')

或者更具体,可能

document.querySelector('span.Pattern')

getElementsBy *方法返回HTMLCollections,这可能很难处理。当您想要集合时,请考虑使用querySelectorAll,它返回一个静态NodeList - 与HTMLCollection不同,它可以直接迭代,在迭代时不会改变,而且它更灵活。

或者,当您只选择一个元素时,只需使用.querySelector。

另一方面注意:除非您特别想要获得HTML标记,否则通常更容易使用.textContent而不是.innerHTML

答案 1 :(得分:4)

您可以使用 querySelector 功能选择找到的第一个元素。

console.log(document.querySelector('table tr td span.Pattern').textContent)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<table>
<tbody>
<tr>
<td style="width:70%;">
   <span><i class="glyphicon glyphicon-random"></i></span>
   <span class="Pattern">Geometric Decomposition</span>
</td>
</tr>
</tbody>
</table>

如果您需要访问多个span元素,可以使用 querySelectorAll 函数返回找到的元素的NodeList。

要获得第一个TD,您可以使用函数closest然后执行函数querySelector

Array.prototype.forEach.call(document.querySelectorAll('table tr td span.Pattern'), function(span) {
  console.log(span.closest('tr').querySelector('td').textContent);
  console.log(span.textContent);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
<table>
  <tbody>
    <tr style="background: rgb(243, 236, 236);">
      <td style="width:20%;">1:0</td>
      <td style="width:70%;"><span><i class="glyphicon glyphicon-random"></i></span><span class="Pattern">Geometric Decomposition</span></td>
      <td style="width:10%;">1</td>
    </tr>
    <tr>
      <td style="width:20%;">1:11</td>
      <td style="width:70%;"><span><i class="glyphicon glyphicon-road"></i></span><span class="Pattern">Pipeline</span></td>
      <td style="width:10%;">1</td>
    </tr>
  </tbody>
</table>