代码之家  ›  专栏  ›  技术社区  ›  Nemus

获取输入标记的子元素

  •  0
  • Nemus  · 技术社区  · 6 年前

    <label> 标签就在下面 <input> 标记以用于以后的样式设置。我试过了 .firstElementChild null 价值观。如何获取已单击复选框字段的标签标签?这是我的密码:

    var checkboxes = document.querySelectorAll("input[type='checkbox']");
    
    
    for (var i = 0; i < checkboxes.length; i++) {
      console.log(checkboxes[i]);
      checkboxes[i].addEventListener('change', (e) => {
    
        var targetCb = e.target;
    
        console.log(targetCb.firstElementChild);
    
      });
    }
    <ul>
      <li class="title mb-3">STYLISTIC SET</li>
      <li>
        <input type="checkbox" id="sSet1" name="sSet1" value="sSet1" />
        <label for="sSet1">Stylistic set 1</label>
      </li>
      <li>
        <input type="checkbox" id="sSet2" name="sSet2" value="sSet2" />
        <label for="sSet2">Stylistic set 2</label>
      </li>
      <li>
        <input type="checkbox" id="sSet3" name="sSet3" value="sSet3" />
        <label for="sSet3">Stylistic set 3</label>
      </li>
      <li>
        <input type="checkbox" id="sSet4" name="sSet4" value="sSet4" />
        <label for="sSet4">Stylistic set 4</label>
      </li>
    </ul>
    2 回复  |  直到 6 年前
        1
  •  3
  •   CodeF0x    6 年前

    你好像不知道 child elements siblings

    为儿童考虑以下几点:

    <div id="parent">
      <div id="child">I'm the child of my parent.</div>
    </div>
    

    兄弟姐妹的情况如下:

    <div id="sibling1"></div>
    <div id="sibling2">I'm the sibling of sibling1.</div>
    

    label s是 兄弟姐妹 input 元素。

    console.log(targetCb.firstElementChild); console.log(targetCb.nextElementSibling);

    var checkboxes = document.querySelectorAll("input[type='checkbox']");
    
    
    for (var i = 0; i < checkboxes.length; i++) {
      console.log(checkboxes[i]);
      checkboxes[i].addEventListener('change', (e) => {
    
        var targetCb = e.target;
    
        console.log(targetCb.nextElementSibling);
    
      });
    }
    <ul>
      <li class="title mb-3">STYLISTIC SET</li>
      <li>
        <input type="checkbox" id="sSet1" name="sSet1" value="sSet1" />
        <label for="sSet1">Stylistic set 1</label>
      </li>
      <li>
        <input type="checkbox" id="sSet2" name="sSet2" value="sSet2" />
        <label for="sSet2">Stylistic set 2</label>
      </li>
      <li>
        <input type="checkbox" id="sSet3" name="sSet3" value="sSet3" />
        <label for="sSet3">Stylistic set 3</label>
      </li>
      <li>
        <input type="checkbox" id="sSet4" name="sSet4" value="sSet4" />
        <label for="sSet4">Stylistic set 4</label>
      </li>
    </ul>
        2
  •  0
  •   Yoshimitsu    6 年前

    var targetCb = e.target; var targetCb = e.target.nextElementSibling;