Fearcoder
Fearcoder

Reputation: 788

How can I get the width of the table header and have the same size as the table cell in JQuery?

I have two seperates tables: one for the header and one for the content. This is my table with only headers:

<table class="table table-sm table-bordered >
    <thead>
        <tr>
          <th class="header-length">This is header one</th>            
          <th class="header-length">short</th>      
          <th class="header-length">X</th>            
        </tr>
    </thead>
</table>

And this is my second table with the content

<table class="table table-sm table-bordered>
    <tbody>       
     <tr>     
     <td>This content must align with header one</td>
     <td>very short</td>
      <td>Icon</td>
     </tr>          
    </tbody>
</table>

I want the width of the header to align the content via JQuery I have used this selector to get the property

$('.header-length').width;

The header of the table cell must have the same width as the content whats inside <td>

How can I get the width of the th property to have the same width as the td with JQuery?

Upvotes: 2

Views: 3356

Answers (1)

random
random

Reputation: 7891

width is a function.

You can apply loop to get width of each th.

$('.header-length').each(function() {
    console.log($(this).width());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-sm table-bordered">
  <thead>
    <tr>
      <th class="header-length">This is header one</th>
      <th class="header-length">short</th>
      <th class="header-length">X</th>
    </tr>
  </thead>
</table>

--Edit--

const thWidthArr = [...document.querySelectorAll('.header-length')].map(th => th.offsetWidth);

const table2 = document.querySelectorAll('table')[1];

table2.querySelectorAll('td').forEach((td, i) => {
  td.style.width = thWidthArr[i] + 'px';
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table table-sm table-bordered">
  <thead>
    <tr>
      <th class="header-length">This is header one</th>
      <th class="header-length">short</th>
      <th class="header-length">X</th>
    </tr>
  </thead>
</table>
<table class="table table-sm table-bordered">
  <tbody>
    <tr>
      <td>This content must align with header one</td>
      <td>very short</td>
      <td>Icon</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions