gpt4 book ai didi

JavaScript,获取与 'id'等属性值相同的元素

转载 作者:行者123 更新时间:2023-12-01 00:35:23 25 4
gpt4 key购买 nike

我有一个呈现为以下结构的文档:

<tr>
<td>
<div class="csLabel">
<label for="common_id">Label</label>
</div>
</td>
<td>
<div class="csFields">
<select id="common_id" name="someName">
<option value="">some options...</option>
</select>
</div>
</td>
</tr>

页面上有很多这样的元素,我只想隐藏其中的几个。如您所见,有两个元素:labelselect。它们都共享相同的值 common_id 但在 label 中它被分配给 for 属性,而在 select 中它是 id

有没有办法获取所有使用值 common_id 的此类元素?

最佳答案

尝试一下这个

如果您只想隐藏该行,则只需要 ID:

var id = "common_id2";
[...document.querySelectorAll("#"+id)].forEach(function(ele) {
ele.closest("tr").style.display="none";
})
<table>
<tbody>
<tr>
<td>
<div class="csLabel">
<label for="common_id1">Label</label>
</div>
</td>
<td>
<div class="csFields">
<select id="common_id1" name="someName">
<option value="">some options...</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
<div class="csLabel">
<label for="common_id2">Label</label>
</div>
</td>
<td>
<div class="csFields">
<select id="common_id2" name="someName">
<option value="">some options...</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>

如果标签和元素位于不同行,则需要 ID 和 for=ID

var id = "common_id2";
[...document.querySelectorAll("#" + id + ", [for=" + id + "]")].forEach(function(ele) {
ele.closest("tr").style.display = "none";
})
<table>
<tbody>
<tr>
<td>
<div class="csLabel">
<label for="common_id1">Label</label>
</div>
</td>
</tr>
<tr>
<td>
<div class="csFields">
<select id="common_id1" name="someName">
<option value="">some options...</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
<div class="csLabel">
<label for="common_id2">Label</label>
</div>
</td>
</tr>
<tr>
<td>
<div class="csFields">
<select id="common_id2" name="someName">
<option value="">some options...</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>

关于JavaScript,获取与 'id'等属性值相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58179201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com