If you have an actual String
, then we can take that an load it up into a temporary element to turn it into DOM nodes. Then, we can query the temporary container and get the index quite easily:
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);
}
If you don't have a String
, but instead just have those elements as part of your page, the process is the same, just without setting up the temporary container element:
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>