首页 > 解决方案 > 使用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 元素的类取决于输入类型。

标签: javascripthtmlcssdom-traversal

解决方案


在众多方法中,一种方法如下:

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顾名思义,返回也是元素节点的下一个兄弟节点。

参考:


推荐阅读