2014-02-23 51 views
1

我想一定形式的getElementById,但它顯示錯誤的getElementById在Javascript

遺漏的類型錯誤:對象#有沒有一種方法 '的getElementById'

這裏是我的代碼

varForm = document.forms['newform'].getElementById("yellow"); 
+0

Dom節點沒有getElementById,只能在document(document.getElementById)上使用。如果你需要類似的東西嘗試使用.querySelector(「#黃色」)或.querySelectorAll(「。黃色」) –

回答

2

一個ID是唯一的 - 所以沒有區別(你得到你想要的),直接調用它(/正確):

var Form = document.getElementById("yellow"); 
0
var Form = document.getElementById("yellow"); 

這會得到你的表格。

0

考慮這種形式:

<form id="myform"><input id="lala" type="text" value="123"/></form> 

有幾種方法獲得 「拉拉」 輸入的值:

console.log(document.getElementById("lala").value) 
console.log(document.forms[0].lala.value) 
console.log(document.forms["myform"].lala.value) 
console.log(document.forms.myform.lala.value) 

這裏是Fiddle一起玩。

1

使用以下方法從另一種形式獲取輸入值,例如

形式

<form id="form1"> 
    <input id="txt1" type="text" value="111"/> 
</form> 
<form id="form2"> 
    <input id="txt1" type="text" value="222"/> 
</form> 

的js

//get input value from current form i.e. form 1 
alert(document.getElementById("txt1").value) //111 
//get input value from other form i.e. form2 
alert(document.forms["form2"].txt1.value)  //222 
1

正如其他人所指出的那樣,只要ID是唯一的,我們有getElementByIddocument

varForm = document.getElementById("yellow"); 

但是,如果你仍然堅持查找基於特定dom節點的節點時,可以嘗試:

varForm = document.forms['newform'].querySelector("#yellow");