最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - this.getElementById is not a function - Stack Overflow

programmeradmin1浏览0评论

/

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?

Share Improve this question edited Dec 10, 2019 at 12:15 baDrosa82 asked Dec 10, 2019 at 12:14 baDrosa82baDrosa82 1371 gold badge2 silver badges8 bronze badges 4
  • 6 getElementById is only available on document, 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
Add a ment  | 

3 Answers 3

Reset to default 4

this 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>
发布评论

评论列表(0)

  1. 暂无评论