<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiplication Table</title>
<style type="text/css">
table,th,td{
border: 2px solid black;
border-collapse: collapse;
}
td{
width: 250px;
font-size: 30px
}
</style>
</head>
<body>
<table id="mytable"></table>
<script type ="text/javascript">
var table=document.getElementById('mytable');
var output="";
for(var i=1; i<=10; i++) {
output+="<tr>";
for(var j=1; j<=10; j++) {
output+="<td>"+i*j+"</td>";
}
output+="</tr>"
}
table.innerHTML=output;
</script>
</body>
</html>
The below code is in HTML. I’m using basic javascript code and I’m trying to change the color for row 1 and column 1 numbers from 1-10 to the color blue. It looks like I’m able to render the multiplication number so far, but I am stuck on the logic of changing the colors. I’m assuming you’d have to use an if/else statement.
3
Answers
You know that it’s the first row if
i === 1
. You also know that it’s the first column ifj === 1
.Following this logic, you can add
style='background: blue;'
to every<td>
element if it’s a first row or the first column.Below is an example solution:
This is the most important piece of code here:
You check if it’s a first row or column and based on that you either add the
style
attribute or not. ThecolorStyle
variable is defined earlier as simply:You could give a
class
to<td>
if row (i) is 1 or (||) column (j) is 1:please use correct js Code insertRow() and insertCell() table methods.
the rest is just a matter of mastering CSS with the use of various operators such as: nth-child(n)