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 change getElementbyId to getElementsbyClassName

I’m trying to change the value of colspan using the below code but its only working for January. It should work for both January and February. By clicking the button the value of the colspan attribute, from 2 to 1, of td with id "myTd".

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
}
</style>
</head>
<body>

<p>Click the button to change the value of the colspan attribute, from 2 to 1, of td with id "myTd".</p>

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td id="myTd" colspan="2">January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td id="myTd" colspan="2">February</td>
    <td>$100</td>
  </tr>
</table>
<br> 

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("myTd").colSpan = "1";
}
</script>

</body>
</html>

>Solution :

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

The cause of your issue is because you’ve repeated the same id on multiple elements, which is invalid. id must be unique within the DOM. Change these to common class attributes.

From there you can use querySelectorAll() and loop through the resulting collection to update their colspan:

document.querySelector('button').addEventListener('click', e => {
  document.querySelectorAll(".myTd").forEach(el => el.colSpan = "1");
});
table,
th,
td {
  border: 1px solid black;
}
<p>Click the button to change the value of the colspan attribute, from 2 to 1, of td with id "myTd".</p>

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td class="myTd" colspan="2">January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td class="myTd" colspan="2">February</td>
    <td>$100</td>
  </tr>
</table>
<br>

<button>Try it</button>

Note the use of addEventListener() in the above example. This is an unobtrusive event handler bound in JS code, not HTML. It’s much better practice over using inline onclick attributes.

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