JavaScript basics
document.getElementById()
document.getElementById is quite common in DOM applications. It is used to obtain the element value of a specific id in the page. The syntax similar to document.getElementById also includes documents such as document.getElementByName or document.getElementByTagName. This article focuses on using id. Get the value.
Basic syntax of document.getElementById
document.getElementById("id");
The id in the syntax is a necessary item. Without this item, JavaScript won't know which element to get! Another thing to mention is that document.getElementById will get the first element of the id in the web page, that is, when there are quite a lot of the same id in your page, only the first one will be obtained.
document.getElementById implementation syntax: get text field value
<script language="javascript">
function ShowValue(){
var v=document.getElementById("test").value;
alert(v);
}
</script>
<input type="text" id="test">
<input type="text" id="test">
<input type="button" value="Show me" onclick="ShowValue()">
function ShowValue(){
var v=document.getElementById("test").value;
alert(v);
}
</script>
<input type="text" id="test">
<input type="text" id="test">
<input type="button" value="Show me" onclick="ShowValue()">

We deliberately put two text input fields of input text in the example , and the id is test. When text is entered in both fields and the Show me button is pressed, it is clear that only the first field is displayed. The bits are displayed, so if you want to capture each field, try to set two fields with different ids before executing document.getElementById.
In addition, we used document.getElementById("test").value in the example. The last value means that what we want to get is the field value. Can we write it this way? If what you want to get is div , span , h1... or other elements, of course you don’t have to write it like this, for example.
document.getElementById to get other elements
<script language="javascript">
function ShowValue(){
var v=document.getElementById("test");
alert(v.innerHTML);
}
</script>
<input type="button" value="Show me" onclick="ShowValue()">
<div id="test">How are you.</div>
In this example, we did not use the .value syntax, but directly used document.getElementById("test") to obtain the object HTMLDivElement, and then output the string in the id element through the innerHTML attribute.
function ShowValue(){
var v=document.getElementById("test");
alert(v.innerHTML);
}
</script>
<input type="button" value="Show me" onclick="ShowValue()">
<div id="test">How are you.</div>
Post a Comment
0 Comments