mengmeng
mengmeng

Reputation: 1506

GetElementById in Javascript

I want to getElementById of a certain form but it displays the error

Uncaught TypeError: Object # has no method 'getElementById'

here is my code

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

Upvotes: 1

Views: 1550

Answers (6)

Ayman Morsy
Ayman Morsy

Reputation: 1429

Unlike some other element-lookup methods such as

Document.querySelector() and Document.querySelectorAll(),

getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM.

Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.

So Keep in Your mind about this method:

  • it is called on the document object
  • it returns a single item

Upvotes: 1

Siddique Mahsud
Siddique Mahsud

Reputation: 1453

Use following way to get input values from another form e.g.

Forms

<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

Upvotes: 1

Mehran Hatami
Mehran Hatami

Reputation: 12961

As others have pointed out, as far as Id is unique we have getElementById in document:

varForm = document.getElementById("yellow");

But if you still insist on finding a node based on a specific dom node, you can try:

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

Upvotes: 1

Thomas Junk
Thomas Junk

Reputation: 5676

Consider this form:

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

There are several ways to get the value of the "lala" input:

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)

Here is the Fiddle to play with.

Upvotes: 0

Matt Tabor
Matt Tabor

Reputation: 1053

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

this will get your form.

Upvotes: 0

LarsEngeln
LarsEngeln

Reputation: 288

an ID is unique - so there is no difference (you get what you want), calling it directly(/correctly):

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

Upvotes: 2

Related Questions