首页 > 解决方案 > 如何通过 DOM 在 JavaScript 中获取表格标题单元格的宽度?

问题描述

我可以访问这个 DOM 节点temp1.$el

这是上述变量的内容:

<table id="__BVID__730" aria-busy="false" aria-colcount="10" aria-rowcount="14" class="table b-table table-striped table-hover">
    <thead class="thead-class-hidden">
        <tr>
            <th aria-colindex="1" class="">
                <div style="white-space: nowrap;">
                    Header1 Name
                </div>
            </th>
            <th aria-colindex="2" class="">
                <div style="white-space: nowrap;">
                    Header2 Name
                </div>
            </th>
        </tr>
    </thead>
    <tbody class="">
        <tr class="">
            <td aria-colindex="1" class="">
                <div style="white-space: nowrap;">
                    Row1 Column1 Value
                </div>
            </td>
            <td aria-colindex="2" class="">
                <div style="white-space: nowrap;">
                    Row1 Column2 Value
                </div>
            </td>
        </tr>
    </tbody>
</table>

我正在使用纯 JavaScript,我需要得到的是以下元素的宽度:

 table thead tr th (child-1)
 table thead tr th (child-2)

我尝试了很多事情,例如:

temp1.$el.tHead.firstElementChild.children[0].offsetWidth
temp1.$el.tHead.firstElementChild.children[0].clientWidth    
temp1.$el.tHead.firstElementChild.children[0].firstElementChild.offsetWidth
temp1.$el.tHead.firstElementChild.children[0].firstElementChild.clientWidth

但他们都没有工作。宽度取决于它们内部的table thead tr th实际内容,我需要获取宽度,然后将它们应用到不同的表上。

我设法让它们进入变量temp1.$el,但从这里开始,我无法成功获得我需要的宽度。

标签: javascripthtmlhtml-table

解决方案


您可以使用 ParentNode 属性children完成此操作。

ParentNode属性children是一个只读属性,它返回一个活动的HTMLCollection 其中包含调用它的节点的所有子元素

var element = document.getElementById('__BVID__730');
console.log(element.tHead.children[0].children[0].offsetWidth)
<table id="__BVID__730" aria-busy="false" aria-colcount="10" aria-rowcount="14" class="table b-table table-striped table-hover">
    <thead class="thead-class-hidden">
        <tr>
            <th aria-colindex="1" class="">
                <div style="white-space: nowrap;">
                    Header1 Name
                </div>
            </th>
            <th aria-colindex="2" class="">
                <div style="white-space: nowrap;">
                    Header2 Name
                </div>
            </th>
        </tr>
    </thead>
    <tbody class="">
        <tr class="">
            <td aria-colindex="1" class="">
                <div style="white-space: nowrap;">
                    Row1 Column1 Value
                </div>
            </td>
            <td aria-colindex="2" class="">
                <div style="white-space: nowrap;">
                    Row1 Column2 Value
                </div>
            </td>
        </tr>
    </tbody>
</table>


推荐阅读