Your initial code didn't work because the name attributes in your html were not encased in quotes. They should be:
<div id=test>
<input name="test1" />
<input name="test2" />
</div>
Be aware, that getElementsByName returns a live NodeList of matching elements which is an array-like object even if you expect and receive one result.
If you would like to receive only one element rather than an array containing one element I've provided a couple of alternatives below:
USING THE id ATTRIBUTE: If you know your name will be unique in the whole document, I'd advise using an id instead of the the
name or class attributes. Doing so would allow this:
Html:
<div id=test>
<input id="test1" name="test1"/>
<input id="test2" name="test2"/>
</div>
JavaScript:
document.getElementById("test1");
USING document.querySelector :
If you still need to use the name attribute then you can use
document.querySelector with the following selection
parameter:
document.querySelector('div > input[name="test1"]')
document.querySelector returns the first element in the
document that matches the selection parameter.
In the example above it says, return the first element that is an
input with name attribute equal to "test1" that is a child of a
div.