0

Where can I see more about this? I thought that you had to do document.getElementById always for interacting with an element.

source (Getting data from Google docs into Javascript)

So consider this JavaScript:

function Data(response) {
  document.Team.tName.value = response.feed.entry[0].gs$cell.$t; // HERE !
}

And the following HTML:

<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body>
<table>             
    <form name="Team">
    <tr>                
        <td>
        <input  size="19"  name="tName" readonly >
        </td>               
    </tr>
    </form>
    </table>
<script src="https://spreadsheets.google.com/feeds/cells/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/1/public/values?alt=json-in-script&callback=Data&range=A1"></script>
</body>
</html>
JorgeeFG
  • 5,651
  • 12
  • 59
  • 92
  • There are a handful of ways other than just `.getElementById` that are officially supported, including `getElementsByClassName` and `getElementsByTagName`. – Hamms Jul 11 '17 at 23:37
  • The functionality you've found here where you can reference a named element at `document[name]` is a shorthand commonly used by tutorials, but it isn't officially supported – Hamms Jul 11 '17 at 23:38
  • https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement Using form name and element names has been around since the beginning – epascarello Jul 12 '17 at 00:21

2 Answers2

1

Use the document.querySelector:

function Data(response) {
  document.querySelector('[name=tName]').value = response.feed.entry[0].gs$cell.$t; 
}

document.querySelector

Returns the first Element within the document that matches the specified selector, or group of selectors.


document.querySelector('[name=tName]')

This will select the element with the attribute name and the value tName

Community
  • 1
  • 1
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
0

As other posters have mentioned, there are a few ways to access DOM elements.

If you're just looking at accessing form elements, take a look at HTMLFormElement.elements (MDN).

The HTMLFormElement.elements property returns an HTMLFormControlsCollection (HTML 4 HTMLCollection) of all the form controls contained in the FORM element, with the exception of input elements which have a type attribute of image.

You'll get an neat collection of your form elements, which you can access either directly via their name attributes, or by iterating over the collection.

var formElements = document.querySelector('#some-form').elements;

console.log(formElements['some-form__input-yo'].value); // form element value

// OR

for (let element of formElements) {
   console.log(element.value); // form element value
}

https://jsfiddle.net/93nemsfq/