Sometimes, we want to get child element from event.target
with JavaScript.
In this article, we’ll look at how to get child element from event.target
with JavaScript.
How to get child element from event.target with JavaScript?
To get child element from event.target with JavaScript, we can call querySelector
on event.target
.
For instance, we write:
<form>
<div>
<input />
</div>
<button type="submit">Submit</button>
</form>
to add a form with an input.
Then we write:
const form = document.querySelector('form')
form.onsubmit = (event) => {
event.preventDefault()
console.log(event.target.querySelector('input'));
}
to select the form with querySelector
.
Next, we set form.onsubmit
to a function that gets the input from the form with event.target.querySelector('input')
.
Since the submit event is triggered by the form, event.target
is the form.
Conclusion
To get child element from event.target with JavaScript, we can call querySelector
on event.target
.