Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM Element.Closest Child

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>
    
like image 394
Joe Avatar asked Feb 22 '18 21:02

Joe


1 Answers

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>
like image 94
epascarello Avatar answered Oct 22 '22 10:10

epascarello