Dmitry
Dmitry

Reputation: 14622

How do access to element by name in javascript?

A page has elements without id - only with names. How to access them by javascript like this?

document.getElementById('id').value := "...";

UPDATED:

Thanks to all! Is it possible to access then to element with specified value (radiobutton)?

<nobr><label><input style="vertical-align:middle" type="radio" name="name" value="value1" checked="checked"/><span style="vertical-align:middle" class="label">value1</span></label></nobr><br/>
<nobr><label><input style="vertical-align:middle" type="radio" name="name" value="value2"/><span style="vertical-align:middle" class="label">value2</span></label></nobr><br/>

Upvotes: 2

Views: 2033

Answers (4)

nnnnnn
nnnnnn

Reputation: 150030

The other answers cover your original question. Regarding your update about accessing by value, there is no getElementsByValue() function, but if it is your intention to select the particular radio button that has both a specified name and value you can do something like this:

function getElementByNameAndValue(n, v) {
   var els = document.getElementsByName(n),
       i;

   for (i=0; i < els.length; i++)
      if (els[i].value == v)
         return els[i];

   return null;
}

var r = getElementByNameAndValue("name", "value1");

Above function will return a reference to the first matching element or null if nothing matched. If you want to allow for more than one element with the same name and value you could modify this to return an array (though I don't know why you'd have more than one element with the same name and value, at least not with radio buttons).

Note that also this can easily be modified to return a reference to the currently checked element, just change the if in the loop to be if (els[i].checked).

You may be able to do some or all of this using document.querySelector(), but I don't use it myself because I need to support older IE. You can definitely replace all of the above with one line of jQuery.

Upvotes: 0

Selvakumar Ponnusamy
Selvakumar Ponnusamy

Reputation: 5533

use document.getElementsByName('elementName'). this will give you an array-like collection, get the element by index

Upvotes: 2

RobG
RobG

Reputation: 147403

There is the DOM HTML getElementsByName method that returns a collection of nodes with that name. Note that the name property is not required to be unique, so you may get more than one and that the returned collection is live, so adding or removing elements with the subject name will modify the collection.

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

document.getElementsByName('name')

This returns a nodeList, which you can access like an array.

Upvotes: 6

Related Questions