Three ways to get HTML element values in JavaScript _javascript tips

Source: Internet
Author: User
Tags html form

There are three methods of obtaining elements in javascript:

1, getElementById () method: Get the HTML element by ID.

2, Getelementsbyname () method: to get the element by name, is an array.

3, getElementsByTagName () method: The HTML tag to get the element, is an array.

If you want to get a value, you can use value, such as: Var X=document.getelementbyid ("id"). value;

method One: getElementById () method
You can return a reference to the first object that has the specified ID.

Syntax:document.getElementById (ID)

In DOM programming, it is very common to use. 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 Two: Getelementsbyname () method
because the Name property in a document may not be unique (such as a radio button in an HTML form usually has the same name property), all Getelementsbyname () methods return an array of elements, not an element.

For example, the following code can get the first element named "Inputtext" in the form

var Myparagragh = document.getelementsbyname ("Inputtext") [0].value;

Method Three: getElementsByTagName () method
If you know a lot about the structure of a document, 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 the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.