DOM Element.Closest Child
Asked Answered
A

2

13

When querying the DOM, is there any reason why labels aren't available as children?

var el = document.getElementById("myEl");
var group = el.closest(".form-group");
var ipt =  el.closest(".form-group > input");
var lbl =  el.closest(".form-group > label");
console.log(ipt);
console.log(lbl);
<div class="row">
  <div class="form-group col-sm-6">
    <label>Name
      <i class="fa fa-asterisk text-danger"></i>
    </label>
    <input type="text" class="form-control" id="myEl" value.bind="location.name & validate">
  </div>
</div>
    
Aegospotami answered 22/2, 2018 at 21:24 Comment(3)
because it does not look up the tree than downJainism
Because label is a sibling of the input, not a parent/ancestor developer.mozilla.org/en-US/docs/Web/API/Element/closestSpill
Also, why does it work for the <input>? Note that "The Element.closest() method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter." The <input> itself is returned because it matches the > input selector, but it doesn't match the > label selector.Semipalatinsk
J
21

You need to select the parent and than look for the child, there is no way to combine it. With your code, it is looking for a parent that is an input or a label.

var el = document.getElementById("myEl");
var group = el.closest(".form-group");
var ipt =  group.querySelector("input");
var lbl =  group.querySelector("label");
console.log(ipt);
console.log(lbl);
<div class="row">
  <div class="form-group col-sm-6">
    <label>Name
      <i class="fa fa-asterisk text-danger"></i>
    </label>
    <input type="text" class="form-control" id="myEl" value.bind="location.name & validate">
  </div>
</div>
Jainism answered 22/2, 2018 at 21:30 Comment(1)
You mean select the child, and then look for the parent?Jilolo
J
1

.closest() only searches up the DOM tree, not for siblings, and not down the DOM tree (see W3 resource). Since <label> is a sibling in this case it won't match, even with the child CSS selector you provided.

If you want to use .closest, you can use it to locate a parent of both elements (e.g. .row or .form-group), and use .querySelector on that parent to grab the first matched <label>:

var el = document.getElementById("myEl");
var group = el.closest(".form-group");
var ipt =  el.closest(".form-group > input");
var lbl =  el.closest(".row").querySelector("label");
console.log(ipt);
console.log(lbl);
<div class="row">
  <div class="form-group col-sm-6">
    <label>Name
      <i class="fa fa-asterisk text-danger"></i>
    </label>
    <input type="text" class="form-control" id="myEl" value.bind="location.name & validate">
  </div>
</div>
    
Jilolo answered 13/7, 2024 at 15:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.