JavaScript provides the following ways to get the content of an input field:

Method 1

document.getElementById('textbox_id').value // 获取指定 id 的内容

Example

document.getElementById("searchTxt").value;

Try it »

Note: Methods 2, 3, 4, and 6 below return a collection of elements. Use the index[index]to get the specified element. The first element uses[0], the second element uses[1], and so on...

Method 2

Use the following method to return an HTMLCollection:

document.getElementsByClassName('class_name')[index].value

The HTMLCollection interface represents a generic collection (an array-like object similar to arguments) containing elements (in the order of elements in the document flow), and also provides methods and properties for selecting elements from the collection.

The HTMLCollection in the HTML DOM is live; it updates automatically when the document structure it contains changes.

Example

document.getElementsByClassName("searchField")[0].value;

Method 3

Get an HTMLCollection by tag name:

document.getElementsByTagName('tag_name')[index].value

Example

Get content by the input tag name:

document.getElementsByTagName("input")[0].value;

Method 4

The following returns a NodeList. The NodeList object is a collection of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll.

NodeList is a live collection; that is, if the node tree in the document changes, the NodeList will change accordingly.

document.getElementsByName('name')[index].value

Example

Get content by the name attribute set on the element:

document.getElementsByName("searchTxt")[0].value; // name 属性值为 searchTxt

Method 5

Use CSS selectors to get it; this method is more powerful:

document.querySelector('selector').value // selector 是 CSS 选择器

Example

Example

document.querySelector('#searchTxt').value; // Get by id
document.querySelector('.searchField').value; // Get by class
document.querySelector('input').value; // Get by tag name
document.querySelector('[name="searchTxt"]').value; // Get by name attribute and value

Method 6

querySelectorAll can return all elements matching a CSS selector; it is a NodeList.

document.querySelectorAll('selector')[index].value 

Example

Example

document.querySelectorAll('#searchTxt')[0].value; // Get by id
document.querySelectorAll('.searchField')[0].value; // Get by class
document.querySelectorAll('input')[0].value;  // Get by tag name
document.querySelectorAll('[name="searchTxt"]')[0].value; // Get by name attribute and value

Reference Content