如何动态设置querySelector来读取标题的所有元素?

时间:2017-10-02 09:51:17

标签: loops dom jquery-selectors

我在querySelector上非常基础,所以如果我的问题非常基本但是我无法在线找到解决方案,请原谅

基本上我试图根据它下面的单元格宽度来设置表头的宽度

我到目前为止所做的代码是:

var headerElement = elem.querySelector('thead tr:first-child th:first-child');
var rowElement = elem.querySelector ('tbody tr:first-child td:first-child');

headerElement.style.width = (rowElement.scrollWidth) + 'px';

我想要实现/理解的是如何在该表中通过所有“头对象”进行动态循环,并使用相同的“索引”来迭代该行下面的行:

while (headerElements > i){
var headerElement = elem.querySelector('thead tr:first-child th:i');
    var rowElement = elem.querySelector ('tbody tr:first-child td:i');

    headerElement.style.width = (rowElement.scrollWidth) + 'px';
}

1 个答案:

答案 0 :(得分:0)

我这样解决了:

var header = elem.querySelector('thead tr:first-child');
var row = elem.querySelector ('tbody tr:first-child');
for (i=0;header.cells.length > i;i++){
    header.cells[i].style.width = (row.cells[i].scrollWidth) + 'px';
}