getElementById vs getElementsByName vs getElementsByTagName

Today we will discuss regarding getElementById vs getElementsByName vs getElementsByTagName in JavaScript.

getElementById() :

The getElementById() method returns the element that has the ID attribute with the specified value.

This method is one of the most common methods in the HTML DOM, and is used almost every time you want to manipulate, or get info from, an element on your document.

Returns null if no elements with the specified ID exists.

An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code.

<!DOCTYPE html>
<html>
<body>

<p id="demo">This is the technothirsty.com</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    alert("This is the technothirsty.com");
}
</script>

</body>
</html>
<!-- 
Output:This is the technothirsty.com
-->

 

getElementsByName() :

The getElementsByName() method returns a collection of all elements in the document with the specified name (the value of the name attribute), as a NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

<!DOCTYPE html>
<html>
<body>

<div id="test" name="d1">Dhruv</div>
<div name="d1">Sheth</div>
<button onclick="myFunction()">Try it</button>
  
<script>
function myFunction() {
    var x = document.getElementsByName("d1");
    alert(x[0].innerHTML);
}
</script>
</body>
</html>
<!--
OutPut: Dhruv
-->

getElementsByTagName() :

The getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

<!DOCTYPE html>
<html>
<body>

<div id="test" name="d1">d1</div>
<div name="d2">d2</div>
<button onclick="myFunction()">Try it</button>
  
<script>
function myFunction() {
    var x = document.getElementsByTagName("div");
    alert(x[1].innerHTML);
}
</script>

</body>
</html>
<!--
OutPut: d2
-->

Conclusion:

getElementById fetch element with same ID available in document.

getElementsByName fetch all the elements with given name and returns list of elements.

getElementsByTagName fetch all the elements with given Tag and returns list of elements.

Please give us your valuable feedback to improve quality of post.

Leave a Reply