Hi everyone I am new to js. How to add the same class for all the td using javaScript
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Tic Tac Toe</title>
<link rel="stylesheet" href="style.css"/>
<script src="script.js" defer></script>
</head>
<body>
<h1>Tic Tac Toe</h1>
<table>
<tr>
<td id="c0"></td>
<td id="c1"></td>
<td id="c2"></td>
</tr>
<tr>
<td id="c3"></td>
<td id="c4"></td>
<td id="c5"></td>
</tr>
<tr>
<td id="c6"></td>
<td id="c7"></td>
<td id="c8"></td>
</tr>
</table>
</body>
</html>
I have tried it like this but i am getting this erorr Uncaught TypeError: all.setAttribute is not a function at script.js:9 js
const all = document.querySelectorAll('td');
all.setAttribute('class', 'tds');
You are using querySelectorAll
here, So you will get array like elements of all HTML td
element
You just have to loop over and add class to it
const all = document.querySelectorAll('td');
all.forEach((item, i) => {
item.setAttribute('class', 'tds');
});
You can also use
item.classList.add("tds");
Note: For demo purpose, I've used added text in between td
and some CSS.
const all = document.querySelectorAll('td');
all.forEach((item, i) => {
item.setAttribute('class', 'tds');
});
.tds{
background-color: lime;
}
<h1>Tic Tac Toe</h1>
<table>
<tr>
<td id="c0">c0</td>
<td id="c1">c1</td>
<td id="c2">c2</td>
</tr>
<tr>
<td id="c3">c3</td>
<td id="c4">c4</td>
<td id="c5">c5</td>
</tr>
<tr>
<td id="c6">c6</td>
<td id="c7">c7</td>
<td id="c8">c8</td>
</tr>
</table>
It's very easy using jquery, it can work with a single line of code as seen below
$("td").attr("class", "tds");
/*To show that it works, i added a css code to change the background color so you know it really added the class to the td*/
.tds{
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Tic Tac Toe</h1>
<table>
<tr>
<td id="c0">c0</td>
<td id="c1">c1</td>
<td id="c2">c2</td>
</tr>
<tr>
<td id="c3">c3</td>
<td id="c4">c4</td>
<td id="c5">c5</td>
</tr>
<tr>
<td id="c6">c6</td>
<td id="c7">c7</td>
<td id="c8">c8</td>
</tr>
</table>