I want javascript to automatically add an incrementing numeric id for each of my td elements.
I want a script at the bottom of each HTML page to tell what first id will be input for that page and ++ automaticaly for each next td element. I tried a lot of things with for loop and something is missing with my appendChild method, i just can't make it work but i know i'm almost there.
If someone could give a hand, it would be greatly appreciated!
Here is how a manually enter those IDs each new month :
<tr>
<td id="603" class="offweekend"></td>
<td id="604" class="offmonth"></td>
<td id="605" class="offmonth"></td>
<td id="606" class="offmonth"></td>
<td id="607" class="offmonth"></td>
<td id="608" class="offmonth"></td>
<td id="609" class="weekend">1</td>
</tr>
<script>
tds = document.getElementsByTagName("td");
tdlength = tds.length;
firsttd = 603;
lasttd = firsttd + tdlength;
for (i = firsttd; i < lasttd; i++){
td.appendChild() //???That's where i'm confused, i'm i wrong
with this approach?
}
</script>
//Thank you, i'm still learning :)
Assuming that you have a variable firstValue
that stores what the id of the first td should be, you can use this:
document.querySelectorAll("td").forEach((v,i)=>v.id=i+firstValue);
querySelectorAll
grabs all of the td
elements in order as a NodeList. v
is the td element and i
is the position of the element in the array