Reputation: 7355
I am a very beginner with Javascript and I want to write a script that modifies the style of (some) tables, at the end of the parsing of an html page.
I have a (hopefully) MWE of such script:
<script type="application/javascript">
<!--
var Ri = document.getElementsByTagName("tr");
var Ca = document.getElementsByTagName("td");
var nRi = Ri.length;
var nCa = Ca.length;
var nCo = nCa/nRi;
for (var i = 0; i < nCo; i++)
{
Ca[i].style.backgroundColor="rgb(221,247,255)";
}
for (var i = nCo; i < nCa; i = i+nCo)
{
Ca[i].style.backgroundColor="rgb(221,247,255)";
}
//-->
</script>
but, as you can easily verify, it would work correctly only if there's a single table in the html page.
The question is the following. Let us say there are m tables with the attribute class="tabx"
in the html page. How can I edit the script so that it counts the m tables with the attribute class="tabx"
in the page and, say for j=1,...,m, performs the loops
for (var i = 0; i < nCo; i++)
{
Ca[i].style.backgroundColor="rgb(221,247,255)";
}
for (var i = nCo; i < nCa; i = i+nCo)
{
Ca[i].style.backgroundColor="rgb(221,247,255)";
}
on each of such tables?
Thanks, I couldn't find this in particular on this network with keywords search, and not even in documentation in italian that's plentyful as well...and I know it would take 2 seconds using CSS instead...
Upvotes: 2
Views: 164
Reputation: 766
Here is how you do it.
var t1 = document.getElementsByClassName("tabx");
for(index = 0; index < t1.length; ++index)
{
var Ri = t1[index].getElementsByTagName("tr");
var Ca = t1[index].getElementsByTagName("td");
var nRi = Ri.length;
var nCa = Ca.length;
var nCo = nCa / nRi;
for (var i = 0; i < nCo; i++) {
Ca[i].style.backgroundColor = "rgb(221,247,255)";
}
for (var i = nCo; i < nCa; i = i + nCo) {
Ca[i].style.backgroundColor = "rgb(221,247,255)";
}
}
hope that help.
Upvotes: 1