Three ways to get HTML element value in JavaScript

  • 2021-06-29 09:44:48
  • OfStack

There are three ways to obtain elements in JavaScript:

1. getElementById() method: Obtain the HTML element from id.

2. getElementsByName() method: Get the element through name, which is an array.

3. getElementsByTagName() method: Get the element through the HTML tag, which is an array.

If you want to get a value, you can use value, for example: var x=document.getElementById ("id").value;

Method 1:getElementById() method
Returns a reference to the first object that has the specified ID.

Syntax: document.getElementById (id)

It is very common to use in DOM programming.You can define a tool function so that you can use the getElementById() method with a shorter name.


function id(x){

 if(typeof x == "string"){

 return document.getElementById(x);

 return x;

}

Method 2:getElementsByName() Method
Because name attributes in a document may be more than 1 (for example, a radio button in an HTML form usually has the same name attribute), all getElementsByName () methods return an array of elements instead of an element.

For example, the code below gives you the first name element in form that is "inputText"

var myParagragh = document.getElementsByName("inputText")[0].value;

Method 3:getElementsByTagName() method
If you know the structure of the document well, you can also use the getElementsByTagName () method to get a specific element in the document.

For example, the following code can get the value of the second paragraph in the document:

var myParagragh = document.getElementsByTagName("p")[1].value;


Related articles: