Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add the same class for all the td using javaScript

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');

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading