KarinaKreative
KarinaKreative

Reputation: 39

Find offsetWidth of EACH object in array -- Javascript (NO JQuery)

I've been looking of an answer for this for a few hours:

How can I get the console.log to print the offsetWidth for each td in my table? (WITHOUT using JQuery)

Say I have this table:

                <table>
                    <thead>
                        <tr>
                            <th>One</th>
                            <th>Two</th>
                            <th>Three</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>A One</td>
                            <td>A Two</td>
                            <td>A Three</td>
                        </tr>
                        <tr>
                            <td>B One</td>
                            <td>B Two</td>
                            <td>B Three</td>
                        </tr>
                    </tbody>
                </table>

I want to find the offsetWidth of each of the <td> in the first row.

I've tried this:

var tbodyfistRowCells = tbody.querySelectorAll('tr:first-of-type > td');

for(i = 0; i < tbodyfistRowCells.length; i++){var tbodyColumnWidths = tbodyfistRowCells[i].offsetWidth;}
console.log(tbodyColumnWidths);

It's returning what looks like the offsetWidth of only the last <td>. I need the offsetWidth of every <td>.

I'm new to Javascript. I'm sure I'm missing something obvious and important, I just don't know what to ask the interweb to search for...

Note: The end goal of this is to use the offsetWidth of the <td> to set the width of its respective <th> when the header is fixed to the top of my page (hopefully to override the fixed column width issue). If you can tell me how to use the offsetWidth of one array to change its respective index item in another array (i.e. td[2].offsetWidth = th[2].offsetWidth) that would be a great plus, though obviously not the subject of this question.

Upvotes: 1

Views: 334

Answers (1)

Alex L
Alex L

Reputation: 4241

Try this (Demo - https://codepen.io/Alexander9111/pen/dyPwJvM)

const tbody = document.querySelector('tbody');
const tbodyfistRowCells = tbody.querySelectorAll('tr:first-of-type > td');

for(i = 0; i < tbodyfistRowCells.length; i++){
    var tbodyColumnWidths = tbodyfistRowCells[i].offsetWidth;
    console.log(i, tbodyfistRowCells[i].innerText)
    console.log(i, tbodyColumnWidths)
}

Note I find the <tbody> element first

Console Output:

0 "A One"
0 44
1 "A Two"
1 45
2 "A Three"
2 54

Upvotes: 1

Related Questions