查找HTML标签内容的位置

时间:2019-02-27 20:37:49

标签: javascript html css

我有任务,无法找到方法。

所以,我有这样的字符串:

<td class="class1">
 <span class="class1"></span>
</td>
<td class="class1">
 <span>0</span>
</td>
<td class="class1">
 <span class="class1">1</span>
</td>
<td class="class1">
 <span class="class1">0</span>
</td>

我需要找到字符串中每个span标签内容的索引。

2 个答案:

答案 0 :(得分:0)

我不知道为什么需要这样做,将HTML作为字符串进行操作确实闻起来不是一个好主意,但是,嘿,如果您需要一些代码,请执行以下操作:

const needle = '<span';
const haystack = `<td class="class1">
  <span class="class1"></span>
</td>
<td class="class1">
  <span>0</span>
</td>
<td class="class1">
  <span class="class1">1</span>
</td>
<td class="class1">
  <span class="class1">0</span>
</td>`;
const indices = (new Array(haystack.length))
  .fill()
  .map((_,i) => i)
  .filter(i => haystack.substr(i,needle.length)==needle);

console.log(indices);

答案 1 :(得分:0)

如果您有实际的String,那么我们可以将其加载到一个临时元素中,以将其转换为DOM节点。然后,我们可以查询临时容器并轻松获得索引:

let myString = `<td class="class1">
   <span class="class1"></span>
 </td>
 <td class="class1">
   <span>0</span>
 </td>
 <td class="class1">
   <span class="class1">1</span>
 </td>
 <td class="class1">
   <span class="class1">0</span>
 </td>`;
 
 let tempElement = document.createElement("tr");
 tempElement.innerHTML = myString; // Parse the string as HTML into the row
 let spans = tempElement.querySelectorAll("span"); // Gather up the spans
 
 for(var i = 0; i < spans.length; i++){
   console.log("The span at index " + i + " has text of: " +spans[i].textContent);
 }

如果您没有String,而只是将这些元素作为页面的一部分,则过程是相同的,只是没有设置临时容器元素:

let spans = document.querySelectorAll("span"); // Gather up the spans
 
 for(var i = 0; i < spans.length; i++){
   console.log("The span at index " + i + " has text of: " +spans[i].textContent);
      spans[i].textContent = "Whatever you want";
 }
<table>
  <tr>
    <td class="class1">
     <span class="class1"></span>
    </td>
    <td class="class1">
      <span>0</span>
    </td>
    <td class="class1">
      <span class="class1">1</span>
    </td>
    <td class="class1">
      <span class="class1">0</span>
    </td>
  </tr>
</table>