There are three ways to obtain elements in JavaScript:
1. getElementById() method: get HTML elements through id.
2. getElementsByName() method: get the element through name, which is an array.
3. getElementsByTagName() method: Get elements through HTML tags, which are an array.
If you want to get the value, you can use value, such as: var x=document.getElementById("id").value;
Method 1: getElementById() method
Returns a reference to the first object with the specified ID.
Syntax: document.getElementById(id)
It is very common 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 the name attribute in a document may not be unique (such as radio buttons in HTML forms usually have the same name attribute), all getElementsByName() methods return an array of elements, not an element.
For example, the following code can get the first element in the form whose name is "inputText"
var myParagragh = document.getElementsByName("inputText")[0].value;
Method 3: getElementsByTagName() method
If you know the structure of a document very 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;
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.