We help IT Professionals succeed at work.

GetElementbyName in Javascript

TheCommunicator
on
Hi Guys,

I have following small code snipped in Javascript

 
var something = document.getElementsByName('key');


         for(obj in something) {
                alert(obj.value)

Open in new window


Here the var "Something " definately has tow values and when I do obj.value for each one then it comes back as undefined. BUt when I do something[0].value then it returns the real value.  I am not sure what is wrong with this code?
Comment
Watch Question

Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
var something = document.getElementsByName('key');


         for(i=0;i<something.length;i++) {
obj = something[i];
                alert(obj.value)

Open in new window

Author

Commented:
Thank you so much that worked any reasoning on why the other did nto work?
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
For arrays : http://www.w3schools.com/js/js_loop_for.asp
For objects : http://www.w3schools.com/js/js_loop_for_in.asp

document.getElementsByName('key') return an array

Author

Commented:
Yes but can't is read through that array using for(obj in something)?

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
look like not
Yes, but it's not like a foreach statement.  With javascript's "for x in yyyy", the x iterates through the indexes.  For example:
var myArray = ['foo', 'bar'];
for (obj in myArray) {
  // because this is an array, obj will take the values 0 and 1
  alert(obj);    // iterates through 0 and 1
  }

var myObject = { 'foo': 'bar', 'foo2': 'bar2' };
for (obj in myObject) {
  // now obj will take the index values
  alert(obj);    // iterates through 'foo' and 'foo2'
  }

Open in new window

sorry, I meant to add that in your original example, you would want to write
for(obj in something) {
                alert(something[obj].value)
  }

Open in new window

document.getElementsByName:
Returns a list of elements with a given name in the HTML document.

Syntax
elements = document.getElementsByName(name)
elements is a HTMLCollection of elements.
name is the value of the name attribute of the element.

Example
<!DOCTYPE html>
<form name="up"><input type="text"></form>
<form name="down"><input type="text"></form>
<script>
var up_forms = document.getElementsByName("up");
w(up_forms[0].tagName); // returns "FORM"
</script>

Notes
The name attribute is only applicable to (X)HTML documents. The method returns all elements with a name attribute, such as <meta> or <object> or even if name is placed on elements which do not support a name attribute at all.

document.getElementsByName() returns a HTMLCollection of all the elements with a given value for the name attribute.

Author

Commented:
Thank you so much guys that was useful information.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.