简体   繁体   English

javascript - 在 tbody 中选择节点及其所有子节点

[英]javascript - select nodes and all their child nodes inside tbody

I want to select all elements inside < tbody > and all their sub-elements so i can change a class using javascript.我想选择 < tbody > 中的所有元素及其所有子元素,以便我可以使用 javascript 更改类。

For example, i want to change the class cl1 into cl2 in the following example例如,我想在以下示例中将类 cl1 更改为 cl2

<table>
    <thead>
         ....
    </thead>
    <tbody id="my-table">
        <tr class="cl1 other-class">
            <td>Some value</td>
            <td class="cl1 other-class">Some value</td>
            <td>Some value</td>
        </tr>
        <tr class="cl1 other-class">
            <td class="cl1 other-class">Some value</td>
            <td>Some value</td>
            <td>
                <a class="cl1 link" href="#">Some link</a>
            </td>
        </tr>
    </tbody>

I want to use javascript for this, no jQuery我想为此使用 javascript,没有 jQuery

i managed to select all elements inside < tbody > like this :我设法像这样选择 <tbody> 中的所有元素:

document.getElementById("my-table").tBodies.item(0)

but i didn't know how to select each of their sub-elements or their sub-sub-elements.但我不知道如何选择它们的每个子元素或它们的子子元素。

for changing the class, i know i can use regular expressions to replace the class对于更改类,我知道我可以使用正则表达式来替换类

Possible duplicate How to select all children of an element with javascript and change CSS property?可能重复如何使用 javascript 选择元素的所有子元素并更改 CSS 属性?

try (add an id to your tbody to make this work)尝试(向您的tbody添加一个 id 以使其工作)

var descendants = document.getElementById('tbody').getElementsByTagName("*");
for(var i = 0; i < descendants.length; i++) {
    descendants[i].classList.remove('cl1');
    descendants[i].classList.add('cl2');
}

You said you managed to select <tbody> element, but you wanted to know how to select it's sub-elements or their sub-sub-elements .您说您设法选择了<tbody>元素,但您想知道如何选择它的子元素或其子子元素 You do that with the children property which each element has.您可以使用每个元素具有的children属性来完成此操作。 So this line gives you all children of <tbody> which are the <tr> (rows):所以这一行给了你<tbody>所有子元素,它们是<tr> (行):

document.getElementById("my-table").tBodies.item(0).children;

Then if you get the children of each row, you get the cells.然后如果你得到每一行的孩子,你就会得到单元格。 Example:例子:

var tbody = document.getElementById("my-table").tBodies.item(0);
var rows = tbody.children;
var row1cells = rows[0].children;
var row2cells = rows[1].children;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM