/
let myForm = document.getElementById('myForm')
myForm.addEventListener('submit', function(e){
e.preventDefault()
console.log( this.getElementById('email') )
})
<form id="myForm">
<input type="email" id="email" placeholder="email">
<button type="submit">Send</button>
</form>
Why I can't start from this
to query inside the form?
https://jsfiddle/r3kfjx6a/
let myForm = document.getElementById('myForm')
myForm.addEventListener('submit', function(e){
e.preventDefault()
console.log( this.getElementById('email') )
})
<form id="myForm">
<input type="email" id="email" placeholder="email">
<button type="submit">Send</button>
</form>
Why I can't start from this
to query inside the form?
-
6
getElementById
is only available ondocument
, not on all other nodes. – VLAZ Commented Dec 10, 2019 at 12:15 - I see........ but where can I read more about this? – baDrosa82 Commented Dec 10, 2019 at 12:15
- 1 developer.mozilla/en-US/docs/Web/API/Document/… – takendarkk Commented Dec 10, 2019 at 12:16
- there should only be one element with a particular id in the document so no need to go into your form to get it – Pete Commented Dec 10, 2019 at 12:25
3 Answers
Reset to default 4this
refers to the form element. As getElementById()
is only available on document
object, you can not use getElementById()
on other element. Try querySelector()
instead:
let myForm = document.getElementById('myForm')
myForm.addEventListener('submit', function(e){
e.preventDefault()
console.log( this.querySelector('#email') )
})
<form id="myForm">
<input type="email" id="email" placeholder="email">
<button type="submit">Send</button>
</form>
In this context, this
is HTMLFormElement
, not document
:
let myForm = document.getElementById('myForm')
myForm.addEventListener('submit', function(e) {
e.preventDefault();
alert(this);
})
<form id="myForm">
<input type="email" id="email" placeholder="email">
<button type="submit">Send</button>
</form>
let myForm = document.getElementById('myForm')
myForm.addEventListener('submit', function(e){
e.preventDefault()
console.log( document.getElementById('email') )
})
<form id="myForm">
<input type="email" id="email" placeholder="email">
<button type="submit">Send</button>
</form>