javascript - 使用javascript定位表内的所有标签
问题描述
我有以下设置。在这里,我正在尝试添加自定义单选和复选框。
Array.from(document.querySelectorAll("tr")).forEach((tr,index)=>{
var mark=document.createElement("span");
Array.from(tr.querySelectorAll("input")).forEach((inp,index1)=>{
if(inp.type=="radio"){
mark.classList.add("dotmark");
inp.parentNode.appendChild(mark);
}
else{
mark.classList.add("checkmark");
inp.parentNode.appendChild(mark);//instead append in to the next td's label tag
}
})
})
span{
width:20px;
height:20px;
background:#ccc;
display:inline-block;
}
<table id="tab1" class="table labelCustom">
<tbody>
<tr><td><input type='radio' id='one' name='name'></td><td><label for='one'>example</label></td></tr>
<tr><td><input type='radio' id='two' name='name'></td><td><label for='two'>example</label></td></tr>
<tr><td><input type='radio' id='three' name='name'></td><td><label for='three'>example</label></td></tr>
</tbody>
</table>
我希望将动态创建的跨度元素插入标签标签中。现在它把它插入到输入 td 中。
注意:span 元素的类取决于输入类型。
解决方案
在众多方法中,一种方法如下:
Array.from(document.querySelectorAll("tr")).forEach((tr, index) => {
var mark = document.createElement("span");
Array.from(tr.querySelectorAll("input")).forEach((inp, index1) => {
// caching the <label> element for readability:
let label = inp.parentNode.nextElementSibling.querySelector('label');
// adding the class-name based on the result of the ternary operator,
// if the input.type is equal to 'radio' we return the class-name of
// 'dotmark', otherwise we return 'checkmark':
mark.classList.add(inp.type === 'radio' ? 'dotmark' : 'checkmark');
// appending the element held within the 'mark' variable:
label.appendChild(mark);
})
})
span {
width: 20px;
height: 20px;
background: #ccc;
display: inline-block;
}
span.dotmark {
background-color: limegreen;
}
span.checkmark {
background-color: #f90;
}
<table id="tab1" class="table labelCustom">
<tbody>
<tr>
<td><input type='radio' id='one' name='name'></td>
<td><label for='one'>example</label></td>
</tr>
<tr>
<td><input type='radio' id='two' name='name'></td>
<td><label for='two'>example</label></td>
</tr>
<tr>
<td><input type='radio' id='three' name='name'></td>
<td><label for='three'>example</label></td>
</tr>
<tr>
<td><input type='checkbox' id='four' name='differentName'></td>
<td><label for='four'>example</label></td>
</tr>
</tbody>
</table>
作为附录,从 OP 对问题的评论:
我试过
nextSibling
了,但没有用,但nextSiblingElement
有效。
两者之间的区别在于,它nextSibling
返回任何兄弟节点,无论是文本节点、元素节点还是任何其他节点,而nextElementSibling
顾名思义,返回也是元素节点的下一个兄弟节点。
参考:
推荐阅读
- c# - 实体框架核心:未处理的异常
- python - Python Tornado - TCPServer 和应用程序
- amazon-web-services - 无法在 Web 浏览器上使用 AWS 公共 DNS 打开 cloudera manager 7180 端口
- linux - MT4/Wine/Ubuntu 将不允许 FileOpen
- apache-kafka - Kafka 1.1.0 中的分区重新分配失败
- typescript - TypeScript 无法返回与泛型参数具有相同基数的对象
- python - 允许 zip 函数将 1D 映射到 2D 数组
- c# - 如何在 Azure 存储帐户表中插入记录。当我运行我的代码 FIXED 时应用程序关闭
- jquery - 如何在没有 React 的情况下订阅多个组件到 Redux 中的操作?
- c# - 仅适用于属性的自定义 XML 序列化