Search code examples
javascripthtmlcsswidth

Setting width of HTML table header elements via JavaScript not updating


I have an HTML table, and since the table headings (<th>) automatically set their own width based on the width of table data (<td>), I am trying to add 10px to whatever value it sets.

Array.from(document.getElementsByTagName("th")).forEach(th => {
    th.style.width = `${parseInt(window.getComputedStyle(th).getPropertyValue("width").split("px")[0]) + 10}px`;
});

Logging my starting and ending width works fine, everything is normal (ie: "14px" to "24px"), the values do get set, as seen in the Chrome Dev Tools, but the actual table on the webpage doesn't update. I tried editing the values via Chrome Dev Tools to large numbers like 1000px and 100%, but that did nothing. Am I missing something?

Note: I'm using Electron, latest, on Windows, latest (but I would assume this is a problem with my general HTML code and doesn't have to do with how Electron works).


Solution

  • You could increase 10px in each 'th' using CSS style, setting the padding of the element.

    <style>
    th { padding: 0px 10px; }
    </style>
    

    If your table is setting to 100% width, and you increase the width of all elements, you will not see the difference, no matter how many pixels you are using to do this.