Receiving name of the element as an object

This is my JavaScript code:

<script>
function change(name){
    var element = document.all.name.value;
}
</script>

It returns an error. How to pass to the function the element's name in order to change its value?

Answers


For a quick fix:

var element = document.all[name].value;

But keep in mind this gets the value, not the element itself. To get the element, then change the value, do:

var element = document.all[name];
element.value = 'whee';

Also, you should consider using another way to access the elements instead of document.all. Look into using IDs instead of names with the document.getElementById() function. See this JavaScript best practices list.

As Peter Bailey points out in his answer, many HTML elements can have the same name. This is one reason why document.getElementById() is preferable: element IDs are unique (in valid HTML, of course).


If by "name" you mean "name attribute", you have to understand that names are not unique to an HTML document. They need context.

Although you can use document.all - that is non-standard and only works in IE. You'll be better off using a more cross-browser friendly mechanism.

Typically, name attributes will belong to elements in a form, such as <input/> and <select> elements. The names of these elements are exposed as properties of the <form>'s elements property in the DOM.

If you can get access to the form's DOM object, then you can access its elements' DOM objects too.

An example

<form id="foo">
  <input type="text" name="test" />
</form>

<span onclick="change( 'foo', 'test' );">Change Value</span>

<script type="text/javascript">

function change( formId, elementName )
{
  // Get the form's DOM object
  var f = document.getElementById( formId );

  // Get the element's DOM object
  var element = f.elements[elementName];

  // Modify the element's value property
  element.value = 'Hello World';

  // Note, the above 3 lines can be refactored to this
  // document.getElementById( formId ).elements[elementName].value = 'Hello World';
}

</script>

Need Your Help

What is the correct content-type header for Json RPC v2 over HTTP?

json http http-headers content-type json-rpc

I know that JSON RPC is no hard spec, but I cannot find a proper solution on this. The question is what content-type is/are correct:

Is there a Java local queue library I can use that keeps memory usage low by dumping to the hard drive?

java queue message-queue

This maybe not possible but I thought I might just give it a try. I have some work that process some data, it makes 3 decisions with each data it proceses: keep, discard or modify/reprocess(becaus...