javascript - 如何通过 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
,但从这里开始,我无法成功获得我需要的宽度。
解决方案
您可以使用 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>
推荐阅读
- c# - 在我的 dot net 程序中收到“进程无法访问该文件,因为它正被另一个进程使用”的错误
- windows - 在 Go 中调用 windows API 时如何获取 Windows 系统错误代码
- r - 基于另一个值的重复序列
- flutter - 如何在不使用 Flutter 擦除 Firestore 中的所有其他数据的情况下更新数据?
- typescript - 在打字稿中实现一个集合,特别是 IterableIterator<[T, T]>
- c# - 在 Unity 中删除带有一个参数的侦听器
- augmented-reality - 如何在 Reality Composer 中以 USDZ 格式导出?
- c# - 在 Windows 10 上运行 .NET 3.5 应用程序,无需安装任何东西或发送 app.config
- laravel - Laravel - 在尝试方法上禁用散列
- c# - 资源不包含菜单的定义