The document.getElementById() method returns the element of the given id.
In the example below, we will use this method to access the value of some element by its ID i.e. document.getElementById("ID").value.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript DOM getElementbyId Method </title>
</head>
<body>
<h2>Square Number</h2>
<script>
function getsquare(){
var number=document.getElementById("number").value;
alert("Square of " + number + " is " + number*number);
}
</script>
<form>
Enter No : <input type="text" id="number" name="number"/>
<input type="button" value="Square" onclick="getsquare()"/>
</form>
</body>
</html>
Output
JavaScript DOM getElementbyId Method Example
JavaScript document.getElementsByName()
The document.getElementsByName() method returns all the element of a specified name.
Syntax
document.getElementsByName("name")
In this example, all <input> elements with same type in the document that have a same
name attribute will get stored in an array variable.
By that using that array we'll check all the checkboxes with same name. Have a look at example below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript DOM getElementsByName() Method </title>
</head>
<body>
Samsung: <input name="Smartphone" type="checkbox" value="Samsung">
OnePlus: <input name="Smartphone" type="checkbox" value="OnePlus">
<p>Click the button to check all checkboxes that have a name attribute with the value "Smartphone".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementsByName("Smartphone");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].type == "checkbox") {
x[i].checked = true;
}
}
}
</script>
</body>
</html>
Output
JavaScript DOM getElementsByName() Method
Samsung:
OnePlus:
In this example, by using the length attribute i.e. document.getElementById.length, we'll calculate
total no. of elements having same name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> getElementsByTagName() Method Display List </title>
</head>
<body>
<ul type="circle">
<li>Samsung</li>
<li>OnePlus</li>
<li>Google Pixel</li>
</ul>
<button onclick="display()">Try it</button>
<p id="demo"></p>
<p>Click the button to display the innerHTML of the second li element (index 2).</p>
<script>
function display() {
var x = document.getElementsByTagName("LI");
document.getElementById("demo").innerHTML = x[2].innerHTML;
}
</script>
</body>
</html>
Output
getElementsByTagName() Method Display List Examples