Get child element from event.target

49,924

You can use the documentElement.querySelector() method.

function onSubmit(event){
    console.log(event.target.querySelector('input'));

}

You can use any valid CSS query to get the element you need

Share:
49,924
mikebrsv
Author by

mikebrsv

Updated on January 04, 2021

Comments

  • mikebrsv
    mikebrsv over 3 years

    event.target returns the DOM element an action was performed on. How do I get a specific child element from the output?

    Here's my form (with Angular markup):

    <form (ngSubmit)="onSubmit($event)" id="kekpek">
      <div class="form-group">
        <label>Example file input</label>
        <input type="file" class="form-control-file" #fileupload [(ngModel)]="myFile" name="myFile" (change)="fileChange($event)"/>
      </div>
      <button type="submit" class="btn btn-success">Submit</button>
    </form>
    

    It fires the function:

    onSubmit(event) {
        console.log(event.target);
    }
    

    Which output the entire form. I need to access the input element in the onSubmit() function.

    • Austin Brunkhorst
      Austin Brunkhorst over 6 years
      How do you identify this specific child element? As it stands, we don't have enough information to help you.
    • Ben Kolya Mansley
      Ben Kolya Mansley over 6 years
      You can use event.target.children to get a list of children (if that wasn't obvious)!
    • Arun P Johny
      Arun P Johny over 6 years
      you can use the query api on the element
  • Nicolai Lissau
    Nicolai Lissau over 5 years
    And event.target.querySelector('input').value will give you the content of input
  • Ben Racicot
    Ben Racicot almost 5 years
    It also doesn't get an element's children like the question asked.
  • Chirag Ravindra
    Chirag Ravindra almost 5 years
    @BenRacicot The text of the question says How do I get a specific child element from the output? which is what the answer above tries to solve. If you want all the children, you can just use ParentNode.children