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

Setting colspan with Javascript on certain td (without any id)

I need to apply some CSS/JS on an existing web page. Within it there is

<tr foodtablesupper>
  <td class="subheader" colspan="3">
    Upper Floor
  </td>
</tr>
<tr foodchoice>
  <td class="dish-1">
    Coleslaw
  </td>
  <td class="dish-2">
    Porridge
  </td>
</tr>
<tr foodtablesupper>
  <td class="subheader" colspan="3">
    Mezzanine Floor
  </td>
</tr>

I need to change the colspan to 4. How can I address the td and how do I change the colspan attribute just using vanilla-JS?

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 :

It’s your decision actually what selector to use to address your colspanned TD based on the its page context. It should unique enough. I’ve chosen it to be in your TR with foodtablesupper attribute.
There’s not enough surrounding markup in your example.
UPDATE
Edited the code to address possible several TDs as the author asked.

document.querySelector('button').addEventListener('click', () => {

  document.querySelectorAll('tr[foodtablesupper] > td.subheader').forEach(td => td.setAttribute('colspan', 4));

});
td{
  min-width:50px;
  background:#aaa;
  text-align:center;
}
table{
  border-spacing: 3px;
}
td.subheader{
  background: yellow;
}
<table>
<tr foodtablesupper>
  <td class="subheader" colspan="3">
    Upper Floor
  </td>
</tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
</table>
<hr/>
<button>Make 4 colspan</button>
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