admin管理员组文章数量:1406945
/
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>
本文标签: javascriptthisgetElementById is not a functionStack Overflow
版权声明:本文标题:javascript - this.getElementById is not a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744944375a2633683.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论