1

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");
1
  • Dom nodes don't have getElementById, that can be used only on document (document.getElementById). If you need something like that try to use .querySelector("#yellow") or .querySelectorAll(".yellow") Commented Feb 23, 2014 at 10:11

6 Answers 6

2

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

var Form = document.getElementById("yellow");
Sign up to request clarification or add additional context in comments.

Comments

1

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");

Comments

1

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

Comments

1

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

Comments

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

this will get your form.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.